C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
This method randomly rearranges the letters in a string. It shuffles the letters for a word game or other simple application. It can help find new hash codes from the same string. This implementation can be adapted to other problems.
Example. First, this solution uses LINQ and the method syntax. This is not a cryptographic or casino-quality algorithm, but for quick applications, it works great. It uses OrderBy along with the new string constructor.
C# program that randomizes strings using System; using System.Linq; class Program { static void Main() { // The source string const string original = "senators"; // The random number sequence Random num = new Random(); // Create new string from the reordered char array string rand = new string(original.ToCharArray(). OrderBy(s => (num.Next(2) % 2) == 0).ToArray()); // Write results Console.WriteLine("original: {0}\r\nrand: {1}", original, rand); Console.Read(); } } Output original: senators rand: tossenar
We see that char arrays are enumerable, meaning when you apply foreach or OrderBy, you individually get each letter. This is just what we need. This is the LINQ method syntax, which combines the OrderBy with a lambda expression.
Also: You could use the query syntax instead. This is clearer in some program contexts.
Finally: ToArray converts the enumerable letters in the statement to a string again, producing the final result: a randomized string.
Summary. We used OrderBy to randomize the characters in a string. This style of code could be used in much more serious systems. It is interesting to experiment with, but also has some drawbacks—it does not randomize as well as other algorithms.