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)
我用这个扩展完成了这个:
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)
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)
你正在寻找像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)