svetlozar_kirkov

Shuffle Strings

Oct 7th, 2014
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.56 KB | None | 0 0
  1. using System;
  2. using System.Linq;
  3.  
  4. internal class ConsoleTests
  5. {
  6.  
  7.     public static string ShuffleString(string stringToShuffle)
  8.     {
  9.         if (String.IsNullOrEmpty(stringToShuffle))
  10.         {
  11.             throw new ArgumentNullException("stringToShuffle",
  12.                 "The stringToShuffle variable must not be null or empty");
  13.         }
  14.  
  15.         return new string(
  16.             stringToShuffle
  17.                 .OrderBy(character => Guid.NewGuid())
  18.                 .ToArray()
  19.             );
  20.     }
  21.  
  22.     public static string ShuffleStringExcludeOriginal(string stringToShuffle)
  23.     {
  24.         string shuffled;
  25.  
  26.         if (String.IsNullOrEmpty(stringToShuffle))
  27.         {
  28.             throw new ArgumentNullException("stringToShuffle",
  29.                                             "The stringToShuffle variable must not be null or empty");
  30.         }
  31.  
  32.         if (stringToShuffle.Length < 2)
  33.         {
  34.             throw new ArgumentException("This method can not be used when the string to shuffle is less than two " +
  35.                                         "characters long as it is not possible to exclude the original",
  36.                                         "stringToShuffle");
  37.         }
  38.  
  39.         do
  40.         {
  41.             shuffled = new string(
  42.                                     stringToShuffle
  43.                                         .OrderBy(character => Guid.NewGuid())
  44.                                         .ToArray()
  45.                                     );
  46.         } while (shuffled == stringToShuffle);
  47.  
  48.         return shuffled;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment