Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random string with no duplicates

I'm trying to generate a 16 chars random string with NO DUPLICATE CHARS. I thoght that it shouldn't be to hard but I'm stuck.

I'm using 2 methods, one to generate key and another to remove duplicate chars. In main I've created a while loop to make sure that generated string is 16 chars long.

There is something wrong with my logic because it just shoots up 16-char string with duplicates. Just can't get it right.

The code:

public string RemoveDuplicates(string s)
{
    string newString = string.Empty;
    List<char> found = new List<char>();
    foreach (char c in s)
    {
        if (found.Contains(c))
            continue;

        newString += c.ToString();
        found.Add(c);
    }
    return newString;
}

public static string GetUniqueKey(int maxSize)
{
    char[] chars = new char[62];
    chars =
    "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
    byte[] data = new byte[1];
    RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
    crypto.GetNonZeroBytes(data);
    data = new byte[maxSize];
    crypto.GetNonZeroBytes(data);
    StringBuilder result = new StringBuilder(maxSize);
    foreach (byte b in data)
    {
        result.Append(chars[b % (chars.Length)]);

    }
    return result.ToString();
}

string builder = "";

do
{                       

    builder = GetUniqueKey(16);
    RemoveDuplicates(builder);

    lblDir.Text = builder;
    Application.DoEvents();


} while (builder.Length != 16);
like image 286
Ladislav Biskupec Avatar asked Mar 03 '13 11:03

Ladislav Biskupec


People also ask

Can we generate random string?

Using Java 8 StreamYou can also generate a random alphanumeric string of fixed length using streams in Java. A random string is generated by first generating a stream of random numbers of ASCII values for 0-9, a-z and A-Z characters.

Which string function returns a random number?

random() method generates the random number between 0 and 1. In toString(36) method, 36 represents base 36. The toString(36) represents digits beyond 9 by letters. The substring(2, 7) method returns five characters.

What is random string?

Random strings can be unique. Used in computing, a random string generator can also be called a random character string generator. This is an important tool if you want to generate a unique set of strings. The utility generates a sequence that lacks a pattern and is random.


2 Answers

Consider implementing shuffle algorithm with which you will shuffle your string with unique characters and then just pick up first 16 characters.

You can do this in-place, by allocating single StringBuffer which will contain your initial data ("abc....") and just use Durstenfeld's version of the algorithm to mutate your buffer, than return first 16 chars.

like image 101
Marcin Deptuła Avatar answered Oct 06 '22 02:10

Marcin Deptuła


There are many algorithms for this.

One easy one is:

  1. Fill an array of chars with the available chars.
  2. Shuffle the array.
  3. Take the first N items (where N is the number of characters you need).

Sample code:

using System;

namespace ConsoleApplication2
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
            Random rng = new Random();

            for (int i = 0; i < 10; ++i)
            {
                string randomString = RandomString(16, chars, rng);
                Console.WriteLine(randomString);
            }
        }

        public static string RandomString(int n, char[] chars, Random rng)
        {
            Shuffle(chars, rng);
            return new string(chars, 0, n);
        }

        public static void Shuffle(char[] array, Random rng)
        {
            for (int n = array.Length; n > 1; )
            {
                int k = rng.Next(n);
                --n;
                char temp = array[n];
                array[n] = array[k];
                array[k] = temp;
            }
        }
    }
}
like image 21
Matthew Watson Avatar answered Oct 06 '22 03:10

Matthew Watson