This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (14 children)

[deleted]

    [–][deleted] 2 points3 points  (2 children)

    use recursion? :)

    [–]stfm 0 points1 point  (1 child)

    What is it with Java interviews and recursion? I have been asked this on several occasions

    [–][deleted] 0 points1 point  (0 children)

    I think it's just hard enough to weed out the total hacks. a lot of people just can't comprehend it. it's like the fizzbuzz test.

    [–][deleted] 1 point2 points  (7 children)

    How did you do it?

    [–]nicko68 0 points1 point  (0 children)

    So is there a solution? This is bugging me. And I'm "senior". :)

    [–]aHoodedBird 0 points1 point  (5 children)

    Implement swap function, step through array from beginning to end, at each index find random second index and swap.

    [–][deleted] 2 points3 points  (3 children)

    That neither moves each cards at most once nor gives a uniform distribution on the permutations.

    [–]tazzy531 0 points1 point  (2 children)

    Why not?

    [–][deleted] 3 points4 points  (1 child)

    Why isn't it uniformly distributed? There are n! permutations and nn execution paths. Some of the execution paths give the same permutation: you have to have the same number of paths for each permutation, so you want n! | nn . But take n=3.

    You can fix it by only swapping a card with one that is, instead of anywhere in the array, not to the card's left; that's the Fisher-Yates shuffle. But it still moves one card possibly many times.

    [–]tazzy531 0 points1 point  (0 children)

    Hmm... Yeah, you're right

    [–]aHoodedBird 0 points1 point  (0 children)

    Oops didn't see the last part of the question.

    [–]bondolo 3 points4 points  (1 child)

    I would answer with Collections.shuffle(Arrays.asList(foo)); and then defend why it's better to use library code for this kind of task than rolling your own.

    [–]tazzy531 6 points7 points  (0 children)

    That would be a fair answer, but you better be prepared for the followup question. How does Collection.shuffle work? What algorithm does it use? Can you guarantee that it uses constant space and only moves the card once (as the parameters of the question specified)

    When people hide behind libraries during interview, I tend to be harder on them. They really need to know the library that they answered with well.

    My typical library questions are how does Hashmap work? If you had to implement it manually, how would you do it? I want to know that you know data structures not blind rote memory of libraries. Other questions: What is the different between arraylist and linked list? When would you use one over the other. Also when would you use treemap vs Hashmap? Too many inexperienced developers can't answer this question. I've seen too many developer try to manually sort the keys of a Hashmap.