Best shuffle: Difference between revisions

Content added Content deleted
(→‎{{header|Java}}: fix randomization bug)
Line 1,571: Line 1,571:
=={{header|Java}}==
=={{header|Java}}==
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
Translation of [[Best_shuffle#Icon_and_Unicon|Icon]] via [[Best_shuffle#AWK|AWK]]
<lang java>import java.util.*;
<lang java>import java.util.Random;


public class BestShuffle {
public class BestShuffle {
Line 1,583: Line 1,583:
public static String bestShuffle(final String s1) {
public static String bestShuffle(final String s1) {
char[] s2 = s1.toCharArray();
char[] s2 = s1.toCharArray();
Collections.shuffle(Arrays.asList(s2));
shuffle(s2);
for (int i = 0; i < s2.length; i++) {
for (int i = 0; i < s2.length; i++) {
if (s2[i] != s1.charAt(i))
if (s2[i] != s1.charAt(i))
Line 1,597: Line 1,597:
}
}
return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")";
return s1 + " " + new String(s2) + " (" + count(s1, s2) + ")";
}

public static void shuffle(char[] text) {
Random rand = new Random();
for (int i = text.length - 1; i > 0; i--) {
int r = rand.nextInt(i + 1);
char tmp = text[i];
text[i] = text[r];
text[r] = tmp;
}
}
}