3.7.3 单词乱序

2013-10-07 14:43:46 · 作者: · 浏览: 62

3.7.3  单词乱序

有了给玩家猜测的单词后,现在需要生成一个该单词的乱序版本。

  1. string jumble = theWord; // jumbled version of word  
  2. int length = jumble.size();  
  3. for (int i = 0; i < length; ++i)  
  4. {  
  5. int index1 = (rand() % length);  
  6. int index2 = (rand() % length);  
  7. char temp = jumble[index1];  
  8. jumble[index1] = jumble[index2];  
  9. jumble[index2] = temp;  
  10. }  

上面的代码将单词复制到jumble用于乱序。程序生成了string对象中的两个随机位置,并交换这两个位置的字符。交换操作的次数等于单词的长度。