Skip to content

Instantly share code, notes, and snippets.

@Satal
Last active December 22, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Satal/6446408 to your computer and use it in GitHub Desktop.
Save Satal/6446408 to your computer and use it in GitHub Desktop.
Shuffle the characters in a string but excluding the original string that was passed in. The method checks that we have passed in a string of more than two characters as if we have less than two characters it is not possible to return anything but the original string.
public static string ShuffleStringExcludeOriginal(string stringToShuffle)
{
    string shuffled;
 
    if (String.IsNullOrEmpty(stringToShuffle))
    {
        throw new ArgumentNullException("stringToShuffle",
                                        "The stringToShuffle variable must not be null or empty");
    }
 
    if (stringToShuffle.Length < 2)
    {
        throw new ArgumentException("This method can not be used when the string to shuffle is less than two " +
                                    "characters long as it is not possible to exclude the original",
                                    "stringToShuffle");
    }
 
    do
    {
        shuffled = new string(
                                stringToShuffle
                                    .OrderBy(character => Guid.NewGuid())
                                    .ToArray()
                                );
    } while (shuffled == stringToShuffle);
 
    return shuffled;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment