0

我编写代码来打乱单词我正在创建简单的游戏混乱

         string jumble = theWord;
         int length = jumble.Count();
         for (int i = 0; i < length; ++i)
         {
             int index1 = (rand.Next() % length);
             int index2 = (rand.Next() % length);

             char  temp =jumble[index1];
             jumble = jumble.Replace(jumble[index1], jumble[index2]);
             jumble = jumble.Replace(jumble[index1], temp);

         }

更新代码

         string jumble = theWord;
         int length = jumble.Count();
         for (int i = 0; i < length; ++i)
         {
             int index1 = (rand.Next() % length);
             //int index2 = (rand.Next() % length);

         char temp = jumble[index1];
         jumble[i] = jumble[index1 - 1];
         jumble[i] = temp;

         }

错误 1 ​​属性或索引器 'string.this[int]' 无法分配给 - 它是只读的

4

3 回答 3

5

为了排列的清晰和良好的分布,我会选择这个(可能是出于性能考虑):

public static class Ext
{
    private static Random rand = new Random();

    public static string Shuffle(this String str)
    {
        var list = new SortedList<int,char>();
        foreach (var c in str)
            list.Add(rand.Next(), c);
        return new string(list.Values.ToArray());
    }
}
  • 注意其他答案:一个是严重偏见,另一个不会给出所有可能的洗牌。这些都是有效的答案,但如果你不关心这种东西。
于 2012-11-12T05:28:02.787 回答
4
         StringBuilder jumbleSB = new StringBuilder();
         jumbleSB.Append(theWord);
         int lengthSB = jumbleSB.Length;
         for (int i = 0; i < lengthSB; ++i)
         {
             int index1 = (rand.Next() % lengthSB);
             int index2 = (rand.Next() % lengthSB);

             Char temp = jumbleSB[index1];
             jumbleSB[index1] = jumbleSB[index2];
             jumbleSB[index2] = temp;

         }

         Console.WriteLine(jumbleSB);
    }
于 2012-11-12T04:56:19.930 回答
2
var jumble = new StringBuilder("theWord");
int length = jumble.Length;
var random = new Random();
for(int i=length-1; i>0; i--)
{
    int j = random.Next(i);
    char temp = jumble[j];
    jumble[j] = jumble[i];
    jumble[i] = temp;
}
Console.WriteLine(jumble);
于 2012-11-12T05:10:22.987 回答