Jump to content

Best shuffle: Difference between revisions

1,538 bytes added ,  13 years ago
(→‎Swap if it is locally better algorithm: Task description dictates output format)
Line 767:
a, a (1)
</lang>
 
=={{header|Java}}==
{{trans|AWK}}
<lang java>import java.util.Random;
 
public class BestShuffle {
 
public static void main(String[] args) {
String[] words = {"abracadabra", "seesaw", "grrrrrr", "pop", "up", "a"};
for (String w : words) {
System.out.println(bestShuffle(w));
}
}
 
public static String bestShuffle(String s) {
char[] s1 = s.toCharArray();
char[] s2 = shuffle(s.toCharArray());
for (int i = 0; i < s1.length; i++) {
for (int j = 0; j < s1.length; j++) {
if (i != j && s2[i] != s1[j] && s2[j] != s1[i]) {
char tmp = s2[i];
s2[i] = s2[j];
s2[j] = tmp;
break;
}
}
}
return s + " " + new String(s2) + " (" + count(s1, s2) + ")";
}
 
private static char[] shuffle(char[] chary) {
Random gen = new Random();
for (int i = chary.length - 1; i > 0; i--) {
int r = gen.nextInt(i);
char tmp = chary[r];
chary[r] = chary[i];
chary[i] = tmp;
}
return chary;
}
 
private static int count(char[] ch1, char[] ch2) {
int count = 0;
for (int i = 0; i < ch1.length; i++)
if (ch1[i] == ch2[i]) count++;
return count;
}
 
private BestShuffle() {
}
}</lang>
 
Output:
<pre>abracadabra raaracabdab (0)
seesaw eswaes (0)
grrrrrr rgrrrrr (5)
pop ppo (1)
up pu (0)
a a (1)</pre>
 
=={{header|JavaScript}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.