- Home /
Generate 8 unique random integers
Hey guys, im currently doing a random integers programme. Here's what i got so far
FirstVal=Random.Range(0,numOfPeeps);
SecondVal=Random.Range(0,numOfPeeps);
ThirdVal=Random.Range(0,numOfPeeps);
FourthVal=Random.Range(0,numOfPeeps);
FifthVal=Random.Range(0,numOfPeeps);
SixthVal=Random.Range(0,numOfPeeps);
SeventhVal=Random.Range(0,numOfPeeps);
EightVal=Random.Range(0,numOfPeeps);
while(FirstVal==SecondVal)
{
SecondVal=Random.Range(0,numOfPeeps);
}
if(numOfPeeps>=3){
while(ThirdVal==FirstVal||ThirdVal==SecondVal)
{
ThirdVal=Random.Range(0,numOfPeeps);
}
}
if(numOfPeeps>=4){
while(FourthVal==FirstVal||FourthVal==SecondVal||FourthVal==ThirdVal)
{
FourthVal=Random.Range(0,numOfPeeps);
}
}
if(numOfPeeps>=5){
while(FifthVal==FirstVal||FifthVal==SecondVal||FifthVal==ThirdVal||FifthVal==FourthVal)
{
FifthVal=Random.Range(0,numOfPeeps);
}
}
if(numOfPeeps>=6){
while(SixthVal==FirstVal||SixthVal==SecondVal||SixthVal==ThirdVal||SixthVal==FourthVal||SixthVal==FifthVal)
{
SixthVal=Random.Range(0,numOfPeeps);
}
}
if(numOfPeeps>=7){
while(SeventhVal==FirstVal||SeventhVal==SecondVal||SeventhVal==ThirdVal||SeventhVal==FourthVal||SeventhVal==FifthVal||SeventhVal==SixthVal)
{
SeventhVal=Random.Range(0,numOfPeeps);
}
}
if(numOfPeeps>=8){
while(EightVal==FirstVal||EightVal==SecondVal||EightVal==ThirdVal||EightVal==FourthVal||EightVal==FifthVal||EightVal==SixthVal||EightVal==SeventhVal)
{
EightVal=Random.Range(0,numOfPeeps);
}
}
Comment
Best Answer
Answer by whydoidoit · Jul 24, 2012 at 06:58 PM
using System.Linq;
using System.Collections.Generic;
var availableEntries = Enumerable.Range(1, numOfPeeps).ToList();
firstVal = availableEntries[Random.Range(0, availableEntries.Count)];
availableEntries.Remove(firstVal);
secondVal = availableEntries[Random.Range(0, availableEntries.Count)];
availableEntries.Remove(secondVal);
etcetera...
Or make the list in a random order like this:
var availableEntries = Enumerable.Range(1, numOfPeeps).OrderBy(b=>Random.value).ToList();
firstVal = availableEntries[0];
secondVal = availableEntries[1];
You want a 'deal' function, that's essentially what this OrderBy thing does. Create list of random numbers, sort them, keeping track of their indices. Resulting sorted list has 'random' indices, each, of course, unique.
Answer by glaiveorb · Jul 25, 2012 at 06:14 AM
Hey thanks for the feedback guys! Turns out it was an error with the numOfPeeps as i was not setting it properly!! Thanks btw!!
Your answer
![](https://koobas.hobune.stream/wayback/20220613074635im_/https://answers.unity.com/themes/thub/images/avi.jpg)