3.7.3 单词乱序
有了给玩家猜测的单词后,现在需要生成一个该单词的乱序版本。
- string jumble = theWord; // jumbled version of word
- int length = jumble.size();
- for (int i = 0; i < length; ++i)
- {
- int index1 = (rand() % length);
- int index2 = (rand() % length);
- char temp = jumble[index1];
- jumble[index1] = jumble[index2];
- jumble[index2] = temp;
- }
上面的代码将单词复制到jumble用于乱序。程序生成了string对象中的两个随机位置,并交换这两个位置的字符。交换操作的次数等于单词的长度。