Skip to main content
Code Review

Return to Revisions

3 of 3
replaced http://codereview.stackexchange.com/ with https://codereview.stackexchange.com/

Rolfl's code can be optimized even further by using a variant of the Fisher–Yates / Durstenfeld / Knuth shuffle that initializes the array as it's being shuffled. This saves one array read per iteration and avoids the need for the tmp variable:

private static final class Generator {
 private final Random rand = new Random();
 private final char[] digits = new char[10];
 public final String generate() {
 digits[0] = '0';
 for (int index = 1; index < digits.length; index++) {
 final int pos = rand.nextInt(index + 1);
 digits[index] = digits[pos];
 digits[pos] = (char) ('0' + index);
 }
 return new String(digits);
 }
}

(Caveat: I have neither benchmarked nor even tested this code. That said, I'd expect it to be slightly faster than the original version, although the exact performance may vary depending on compiler and JVM optimizations.)

Ilmari Karonen
  • 3.2k
  • 17
  • 19
default

AltStyle によって変換されたページ (->オリジナル) /