hai friends,

i want one help, how to generate a random numbers without duplication for more than 60 persons. My project is Online Examination in asp.net code behind c#.net.

please help.

Dani AI

Generated

A few practical, reliable options for “unique random numbers for N candidates” beyond the quick suggestions already posted by and .

One easy server-side approach is to create a single random permutation of the integers you need and then assign them in order. That guarantees no duplicates and is O(N). Use the Fisher–Yates shuffle and a cryptographic RNG to avoid seeding pitfalls:

using System.Security.Cryptography;
using System.Linq;

int[] Shuffle(int n)
{
    var arr = Enumerable.Range(1, n).ToArray();
    for (int i = arr.Length - 1; i > 0; i--)
    {
        int j = RandomNumberGenerator.GetInt32(i + 1);
        var tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
    return arr;
}

This is the Fisher-Yates algorithm (proven O(n)). See the algorithm description here: Fisher-Yates shuffle. The RNG helper used above is documented here: RandomNumberGenerator.GetInt32.

If assignments happen on-demand from many concurrent web requests, put the numbers in a table and draw one atomically so two requests cannot get the same value. Example SQL pattern for SQL Server (pick one unassigned row at random and mark it assigned in a single step):

BEGIN TRAN;
WITH pick AS (
  SELECT TOP (1) Id
  FROM SeatNumbers
  WHERE Assigned = 0
  ORDER BY NEWID()
)
UPDATE pick
SET Assigned = 1
OUTPUT inserted.Id;
COMMIT TRAN;

Wrap that in a transaction and add an index on Assigned. For small counts (60+) these are cheap; for very large tables avoid ORDER BY NEWID() for performance.

Notes: persist every assignment so it cannot be reissued after a crash; avoid creating new PRNG instances per request (that can produce duplicates); for tokens instead of numeric IDs consider Guid.NewGuid() or crypto-random bytes for unguessable keys (Guid.NewGuid).

Recommended Answers

All 2 Replies

use the System.Random class in C# its 2 lines of code

Here's what I came up with a while back. You can pass in the length of the string and whether you want to have all lowercase returned.

public static string RandomString(int size, bool lowerCase)
{
   StringBuilder builder = new StringBuilder();
   Random random = new Random();
   char ch ;
   for(int i=0; i<size; i++)
      {
         ch = Convert.ToChar(Convert.ToInt32(26 * random.NextDouble() + 65)) ;
         builder.Append(ch); 
      }
      if(lowerCase)
     return builder.ToString().ToLower();
     return builder.ToString();
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.