Does anybody have a simple method for randomising the character
positions in a string?
Roger Frost - 25 Feb 2008 12:41 GMT
Like a scramble method where "Hello, World!" becomes something like
"leol,H!o rlWd" ?

Signature
Roger Frost
"Logic Is Syntax Independent"
> Does anybody have a simple method for randomising the character
> positions in a string?
>
> *** Sent via Developersdex http://www.developersdex.com ***
Roger Frost - 25 Feb 2008 12:49 GMT
Oh, and at some point will you need to restore the string to it's original
state?

Signature
Roger Frost
"Logic Is Syntax Independent"
> Like a scramble method where "Hello, World!" becomes something like
> "leol,H!o rlWd" ?
Mike P - 25 Feb 2008 12:55 GMT
Roger,
Yes, exactly like that, but I won't need to restore the string to its
original state.
Thanks,
Mike
Marc Gravell - 25 Feb 2008 12:48 GMT
How about (off the top of my head):
public static string Scramble(string input) {
if(string.IsNullOrEmpty(input)) return input; // GIGO
List<char> inputChars = new List<char>(input);
char[] outputChars = new char[inputChars.Count];
Random rand = new Random();
// fill backwards to simplify Rand.Next() logic
for (int i = inputChars.Count - 1; i >= 0; i--)
{
int index = rand.Next(i);
outputChars[i] = inputChars[index];
inputChars.RemoveAt(index);
}
return new string(outputChars);
}
public static void Main()
{
string foo = "The quick brown fox jumps over the lazy
dog";
string bar = Scramble(foo);
}
Marc Gravell - 25 Feb 2008 12:58 GMT
Sorry, should have been Next(i+1), otherwise it always starts with the
last character.
Actually, I'm amazed it didn't throw an exception, passing Next(0)
[although this is covered in the MSDN documentation, still...]
Marc
Mike P - 25 Feb 2008 14:20 GMT
Arne Vajhøj - 26 Feb 2008 03:02 GMT
> Does anybody have a simple method for randomising the character
> positions in a string?
using System;
namespace E
{
public class Program
{
private static Random rng = new Random();
public static void Main(string[] args)
{
string s = "Hello world !";
char[] c = s.ToCharArray();
byte[] b = new byte[c.Length];
rng.NextBytes(b);
Array.Sort<byte, char>(b, c);
string s2 = new string(c);
Console.WriteLine(s2);
Console.ReadKey();
}
}
}
It is not the most efficient method, but the code is simple.
Arne