Randomise character positions in string

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Mike P

    #1

    Randomise character positions in string

    Does anybody have a simple method for randomising the character
    positions in a string?



    *** Sent via Developersdex http://www.developersdex.com ***
  • Roger Frost

    #2
    Re: Randomise character positions in string

    Like a scramble method where "Hello, World!" becomes something like
    "leol,H!o rlWd" ?

    --
    Roger Frost
    "Logic Is Syntax Independent"



    "Mike P" <mike.parr@gmai l.comwrote in message
    news:eHuxrn6dIH A.4144@TK2MSFTN GP05.phx.gbl...
    Does anybody have a simple method for randomising the character
    positions in a string?
    >
    >
    >
    *** Sent via Developersdex http://www.developersdex.com ***

    Comment

    • Marc Gravell

      #3
      Re: Randomise character positions in string

      How about (off the top of my head):

      public static string Scramble(string input) {
      if(string.IsNul lOrEmpty(input) ) return input; // GIGO

      List<charinputC hars = new List<char>(inpu t);
      char[] outputChars = new char[inputChars.Coun t];
      Random rand = new Random();
      // fill backwards to simplify Rand.Next() logic
      for (int i = inputChars.Coun t - 1; i >= 0; i--)
      {
      int index = rand.Next(i);
      outputChars[i] = inputChars[index];
      inputChars.Remo veAt(index);
      }
      return new string(outputCh ars);
      }

      public static void Main()
      {
      string foo = "The quick brown fox jumps over the lazy
      dog";
      string bar = Scramble(foo);
      }

      Comment

      • Roger Frost

        #4
        Re: Randomise character positions in string

        Oh, and at some point will you need to restore the string to it's original
        state?

        --
        Roger Frost
        "Logic Is Syntax Independent"
        Like a scramble method where "Hello, World!" becomes something like
        "leol,H!o rlWd" ?
        >

        Comment

        • Mike P

          #5
          Re: Randomise character positions in string

          Roger,

          Yes, exactly like that, but I won't need to restore the string to its
          original state.


          Thanks,

          Mike



          *** Sent via Developersdex http://www.developersdex.com ***

          Comment

          Working...