0

So, in school we've got this homework where I have to show a shuffled a word and the person have to guess what it's written. However, we haven't been taught about shuffling words and our professor told us to google it. So far, I've read some articles but they're not working, at least in my case.

So, I'd be really happy if someone of you could tell me how to and explain it to me - if you want so.

Neither arrays nor vectors can be used. Thank you!

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245

2 Answers2

0

Well a String is fundamentally an array wrapped in a class, so that's kind of a funny requirement, but you can just shuffle one character at a time for n iterations. Fill in the line where I've left a comment

Random r = new Random (System.currentTimeMillis());
For (int i = 0; i < n; i ++) { // n is your number of iterations 
  int idx = r.nextInt(str.length);
  // use String .substring to move the character at index idx to the end of the string 
}
Lew Bloch
  • 3,364
  • 1
  • 16
  • 10
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
0

Since its an assignment, will give basic explanation and leave you to the implementation.

What you can do is to create/write a swap functionswap(posA,posB,string), that takes two parameter, posA and posB and swap the character in the respectives position in the String 'string'. Loop through all the characters and generate two random number (positions) in each case, then swap the characters:

for (char element : string ){
   swap(genRandom(), genRandom(), string);
}

where genRandom() is a random number generator within the range of the length of the string.

Ibukun Muyide
  • 1,294
  • 1
  • 15
  • 23