随机串c#

ksm*_*wee 15 c# algorithm ironpython

我想知道shuffle string

示例字符串

string word;

//I want to shuffle it
word = "hello"  
Run Code Online (Sandbox Code Playgroud)

我能得到:

rand == "ohlel"
rand == "lleho"
etc.
Run Code Online (Sandbox Code Playgroud)

nan*_*nan 16

这个解决方案(以扩展方法的形式)很好:

    public static string  Shuffle(this string str)
    {
        char[] array = str.ToCharArray();
        Random rng = new Random();
        int n = array.Length;
        while (n > 1)
        {
            n--;
            int k = rng.Next(n + 1);
            var value = array[k];
            array[k] = array[n];
            array[n] = value;
        }
        return new string(array);
    }
Run Code Online (Sandbox Code Playgroud)


Roy*_*ook 9

我用这个扩展完成了这个:

public static class Extensions{
    public static string Scramble(this string s){
        return new string(s.ToCharArray().OrderBy(x=>Guid.NewGuid()).ToArray());
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 说真的,我想知道这有什么问题。它非常快,一行并且易于阅读并且可以正常工作。 (3认同)

Bvd*_*Ven 8

C#:

string str = "hello";

// The random number sequence
Random num = new Random();

// Create new string from the reordered char array
string rand = new string(str.ToCharArray().
                OrderBy(s => (num.Next(2) % 2) == 0).ToArray());
Run Code Online (Sandbox Code Playgroud)

  • 这不会产生良好的随机结果.根据MSDN,OrderBy将使用稳定排序并保留给定相同值的字符的顺序.对于"hello"中的'h'要放在最后,'h'需要滚动'false'而其余'true'.然而结果将是"elloh",这不是很令人兴奋.http://msdn.microsoft.com/en-us/library/bb534966.aspx (8认同)

por*_*ges 5

你正在寻找像Fisher-Yates shuffle这样的东西.该页面上实际上有一个Python示例:

import random

def shuffle(x):
    for i in reversed(range(1, len(x))):
        # pick an element in x[:i+1] with which to exchange x[i]
        j = random.randrange(i+1)
        x[i], x[j] = x[j], x[i]
Run Code Online (Sandbox Code Playgroud)

编辑:由于您的问题都被标记,ironpython并且c#还有一个Java示例,很容易转换为C#.


小智 5

尝试Fisher-Yates Shuffle:

class Shuffle
{
    static System.Random rnd = new System.Random();

    static void Fisher_Yates(int[] array)
    {
        int arraysize = array.Length;
        int random;
        int temp;

        for (int i = 0; i < arraysize; i++)
        {
            random = i + (int)(rnd.NextDouble() * (arraysize - i));

            temp = array[random];
            array[random] = array[i];
            array[i] = temp;
        }
    }

    public static string StringMixer(string s)
    {
        string output = "";
        int arraysize = s.Length;
        int[] randomArray = new int[arraysize];

        for (int i = 0; i < arraysize; i++)
        {
            randomArray[i] = i;
        }

        Fisher_Yates(randomArray);

        for (int i = 0; i < arraysize; i++)
        {
            output += s[randomArray[i]];
        }

        return output;
    }
}

class Program
{
    static void Main()
    {
        string original = "Hello World!";

        string mixedOriginal = Shuffle.StringMixer(original);

        System.Console.WriteLine("The original string: {0}", original);
        System.Console.WriteLine("A mix of characters from the original string: {0}", mixedOriginal);

        System.Console.ReadKey();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 对于算法的想法+1,我们有一个更简短的版本:https://rosettacode.org/wiki/Knuth_shuffle#C.23 (2认同)