Sangeen Khan
Sangeen Khan

Reputation: 175

How to generate Random 26 length character string with no duplicates(characters) in c#?

 Random rnd = new Random();
        string[] coupon = new string[26];
        for (int i = 0; i < coupon.Length; i++)
        {
            coupon[i] = GenerateCoupon(26, rnd);
        }
        textBox1 .Text=(String.Join(Environment.NewLine, coupon));

***** Function***********\

  public static string GenerateCoupon(int length, Random random)
    {
        string characters = "abcdefghijklmnopqrstuvwxyz";
        StringBuilder result = new StringBuilder(length);
        {
            result.Append(characters[random.Next(characters.Length)]);

            return result.ToString();
        }

Strings that code generates :

kheeuasampxqxmoohcrufznugp

vrlncvbftinynhdufjdikacjsi

vblltkxeeapymbprtgaiojqkte

qyfvpcvtazuiodbidcfgwcssgw

ijtlkbrpuyzilndsaqxlrxhggo

emhngmostlapotqziciursddcc

vvflcnewwehgsntstrskbduroe

But i need a code that generates the string that have 26 character length and no duplicate character :

abcdefghijklmnopqrstuvwxyz

zyxwvutsrqponmlkjihgfedcba

mnbvcxzasdfghjklpoiuytrewq

qazwsxedcrfvtgbyhnujmikolp

bhuijnmkoplqazxswedcvfrtgb

Upvotes: 0

Views: 719

Answers (3)

user3437460
user3437460

Reputation: 17474

You can just have a string of a-z. For example: "abcdefghijklmnopqrstuvwxyz".

After that, randomly shuffle the string based on the index of each letter.

Upvotes: 0

EZI
EZI

Reputation: 15364

You can use Fisher-Yates shuffle, or simply

Random rnd = new Random();
var newstr = String.Concat("abcdefghijklmnopqrstuvwxyz".OrderBy(x => rnd.Next()));

Upvotes: 3

Jan van Bloem
Jan van Bloem

Reputation: 65

Take a look at some shuffle algorithms and apply it to your character set.

Upvotes: 0

Related Questions