Home c# How to choose random letters from a string without repeat?

How to choose random letters from a string without repeat?

Author

Date

Category

I did it:

static random rnd = new random ();
  Static String Alphabet = "abcdefghijklmnpqrstuvxwyz";
  String GenerateRandomKey (Int Length)
  {
    StringBuilder Key = New StringBuilder ();
    for (int i = 0; i & lt; length; i ++)
    {
      key.append (Alphabet [RND.NEXT (0, Alphabet.length - 1)]);
    }
    Return key.tostring ();
  }

The problem is that random sometimes displays the same letters, for example abdbdbzzysdhaa (big letters – repetitions). Because of this, my program does not work, as I understood.

On one line should be different letters.


Answer 1, Authority 100%

Judging by example, you need that successive characters do not coincide. To do this, it is enough to exclude the past index value from the generation range

int rn = -1;
for (int i = 0; i & lt; length; i ++)
{
  if (rn & lt; 0)
     rn = rnd.next (0, alphabet.length - 1);
  ELSE.
     rn = (rnd.next (rn + 1, rn + alphabet.length - 1))% alphabet.length;
  key.append (Alphabet [Rn]);
}

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions