Fisher-Yates shuffle. indices . , . , indices, , , -1.
, indices static, , . , indices . 7, , 0100101.
private static int[] indices = { 0, 1, 2, 3, 4, 5, 6 };
protected int getRandomBirthIndex(String s) {
int tmp;
for (int i = 0; i < s.length(); i++) {
int j = randomizer.nextInt(indices.length - i) + i;
if (j != i) {
tmp = indices[i];
indices[i] = indices[j];
indices[j] = tmp;
}
if ((s.charAt(indices[i]) == '1')) {
return indices[i];
}
}
return -1;
}
This approach ends quickly if 1 is dense, guarantees completion after s.length()iterations, even if there are none, and the returned locations are uniform in many units.
source
share