Skip to content

Instantly share code, notes, and snippets.

@t-mart
Created June 5, 2012 19:27
Show Gist options
  • Save t-mart/2877186 to your computer and use it in GitHub Desktop.
Save t-mart/2877186 to your computer and use it in GitHub Desktop.
shuffling
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();
}
}
@winfred
Copy link

winfred commented Jun 6, 2012

btw, if you had a suggestion like this for a real project, i'd have absolutely no qualms about copying your code directly. It's extremely cleaner/better Java. But for a homework like M3, it just felt right to finish my weird/unclean implementation with some inspiration from this instead of copying it directly.

@t-mart
Copy link
Author

t-mart commented Jun 6, 2012

Understood. I take no offense.

There's always more than one way to do it.

@winfred
Copy link

winfred commented Jun 6, 2012

... except there's usually one really good way to do it... like this one... since mine ended up spitting things out backwards I'm just going to use this. Thanks a lot dood. I hope to be equally helpful with the rubies.

@t-mart
Copy link
Author

t-mart commented Jun 7, 2012

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment