Created
June 5, 2012 19:27
-
-
Save t-mart/2877186 to your computer and use it in GitHub Desktop.
shuffling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Random; | |
public class Person2 { | |
/** | |
* This method should take the string | |
* input and return its characters in | |
* random order. | |
* given "gtg123b" it should return | |
* something like "g3tb1g2". | |
* | |
* @param input the string to be modified | |
* @return the modified string | |
*/ | |
private String calc(String input) { | |
//http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#The_modern_algorithm | |
//To shuffle an array a of n elements (indices 0..n-1): | |
//for i from n - 1 downto 1 do | |
//j = random integer with 0 <= j <= i | |
//exchange a[j] and a[i] | |
StringBuilder randomizer = new StringBuilder(input); | |
for (int i = randomizer.length() - 1; i > 0; i--){ | |
int j = new Random().nextInt( i + 1 ); | |
//swap | |
char tmp = randomizer.charAt(i); | |
randomizer.setCharAt(i, randomizer.charAt(j)); | |
randomizer.setCharAt(j, tmp); | |
} | |
return randomizer.toString(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Well, if I'm understanding you correctly, if a string is constructed randomly (which I think your implementation was), then backwards vs forwards makes no difference right?
However, if you still decide to use mine, I've discovered a bug in it. Random().nextInt(n) chooses from [0, n). But according to the algorithm, this needs to be [0, n] (inclusive of both zero and n), so you need to change the nextInt call to nextInt( i + 1 ).
This is a prime example of "bias" that I was talking about about the meeting. Little bugs like this can cause a certain set of permutations to be more likely than others. In this example, there would always be 1 position that was improperly excluded from the possibility of of being swapped.
Hehe, now, do you need this kind of randomness for something as silly as this assignment? Nope.