I have an assignment in which we are instructed to create a method which takes a string, scrambles the content of the string, and then returns the scrambled string (ie "Hello" returns "elloH"). However, we are only allowed to do this via loops and basic string functions (no arrays can be used).
My Teacher has left the following suggestion for us:
The best way to shuffle is to generate 2 random numbers (index number) and swap the numbers(the content, not the index) based on the random index numbers. Continue to do it for 100 times, they are shuffled and all characters remain the same but in different positions
How would this nessasarily be done? For reference here is my try at the solution, however it does not work and I'm not sure where to go from here:
public void shuffle(String s1) {
int i1 = 0;
int i2 = 0;
String s2 = "";
for(int a2 = 0; a2 < s1.length(); a2++) {
char c1 = s1.charAt(i1);
s2 += c1;
for(int a1 = 0; a1 < 100; a1++) {
double d1 = Math.random();
d1 *= (s1.length()-1);
i1 = (int) d1;
}
}
System.out.println(s2);
}
Aucun commentaire:
Enregistrer un commentaire