2

I want to make an array of random numbers without any duplicate.

private void SetRandomQuestions()
{
    var idS = from t in _db.QuestionsTables
              where t.Cat_Id == _catId
              select new
                     { t.Question_Id };

    // to get the questions Id from database table
    foreach (var variable in idS)
    {
        array.Add(variable.Question_Id);
    }

    // generate a random numbers depends on the array list values
    var random = new Random();

    for (var i = 0; i < _randomQuestionId.Length; i++)
    {
        _randomNumber = random.Next(array.Count);

        for (var j = 0; j < _randomQuestionId.Length; j++)
        {
            if (_randomQuestionId[j] != array[int.Parse(_randomNumber.ToString())])
            {
                _randomQuestionId[i] = array[int.Parse(_randomNumber.ToString())];
                j = 5;
            }
        }
    }
}

As you see here I have list array has values of questions id and further I have created another array to get 4 elements randomly from that array. However, my question is how I can get the elements without any duplicate Ids I have tried many times but unfortunately I didn't success with that.

Raktim Biswas
  • 4,011
  • 5
  • 27
  • 32
Saif Alradhi
  • 129
  • 3
  • 15
  • 1
    Look into array shuffling. – Matthew Aug 29 '15 at 15:50
  • 1
    Can't flag for more duplicates. But there's a dupe [here](http://stackoverflow.com/questions/13195738/avoiding-random-duplicates) and [here](http://stackoverflow.com/questions/14473321/generating-random-unique-values-c-sharp) also [here](http://stackoverflow.com/questions/5561742/generate-distinct-random-numbers-in-c-sharp) then [here](http://stackoverflow.com/questions/4299138/generate-n-random-and-unique-numbers-within-a-range) and probably an other dozen. – Pierre-Luc Pineault Aug 29 '15 at 15:52
  • 1
    And why the heck are converting the numer to string and back? (`int.Parse(_randomNumber.ToString())])`) – Olivier Jacot-Descombes Aug 29 '15 at 16:04
  • Olivier, It was suppose to add values of an array list randomly in array of integers. but I used array shuffling instead of this. – Saif Alradhi Aug 29 '15 at 21:26

3 Answers3

3

The simplest thing would be shuffling your question ids and then taking the first four.

Random rnd = new Random();
randomQuestionId = idS.OrderBy(_ => rnd.Next()).Take(4).ToArray();
Eser
  • 12,346
  • 1
  • 22
  • 32
  • 1
    See [this answer](http://stackoverflow.com/questions/1287567/is-using-random-and-orderby-a-good-shuffle-algorithm) for a more efficient way to shuffle an array (using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle)). – Suigi Aug 29 '15 at 17:00
  • I guess yes, it is the simplest way – Saif Alradhi Aug 29 '15 at 21:21
0

Try this, this code will generate unique random numbers

int smallestNumber = 1;
int biggestNumber = 50;

//Determine the amount of random numbers
int amountOfRandomNumbers = 10;

//Create a list of numbers from which the routine
//shall choose the result numbers
var possibleNumbers = new List<int>();
for (int i = smallestNumber; i <= biggestNumber; i++)
    possibleNumbers.Add(i);

var result = new List<int>();

//Initialize a random number generator
Random rand = new Random();

//For-loop which picks each round a unique random number
for (int i = 0; i < amountOfRandomNumbers; i++)
{
     //Generate random number
     int randomNumber = rand.Next(1, possibleNumbers.Count) - 1;  
     result.Add(possibleNumbers[randomNumber]);       
     //Remove the chosen result number from possible numbers list
     possibleNumbers.RemoveAt(randomNumber);
}

//Now loop on result and print the output

NASSER
  • 5,900
  • 7
  • 38
  • 57
0
var pickFour = array
    .OrderBy(p => Guid.NewGuid())
    .Take(4);
ba__friend
  • 5,783
  • 2
  • 27
  • 20