Generate unique random numbers and sort them.
I'm trying to get 4 unique random numbers out of 1-50. For example, if I get (45,20,1,18), sort them to be (1,18,20,45).
However, my script generates 18 numbers and include the same numbers.
e.g. result{22.29.38.1.13.27.17.37.39.9.17.21.37.39.40.27.29.43} This time, double 17 and 37.
Could you help me to check my script? Why doesn't it work like I expect ?
I'd really appreciate your help!! Thank you.
void Start(){
List<int> fulNumList = new List<int>();
List<int> pickedNumber = new List<int>();
for (int i = 1; i < 50; i++) {
fulNumList.Add(i);
}
//now all possible numbers are in fulNumList
for (int i = 0; i < 3; i++) {
int indexNum = Random.Range(0,fulNumList.Count);
//get a random index number form 0-49
int randomNum = fulNumList [indexNum];
pickedNumber.Add(randomNum);
//store randomNumber into pikedNumber list
fulNumList.RemoveAt(indexNum);
//remove the number that stored in pickedNumber from fulNumList for avoiding repeat numbers
}
pickedNumber.Sort ();
foreach (int result in pickedNumber){
Debug.Log (result);
}
}
Answer by · Jul 21, 2016 at 04:20 PM
I changed this line "for (int i = 0; i < 3; i++)" to "for (int i = 0; i
Thank you for the help! Oh yes! (>=) is right here for 4 numbers.
And...I'm really ashamed to confess what my big problem was. I attached the scrip to 6 of objects, so that I got 6 times of 3 numbers! (18 numbers).
Answer by tippi-co · Jul 22, 2016 at 04:59 AM
Thank you for the help! You have tried my script ! Thank you for taking your time!
Yes, I did mistake that part. I changed it now and I got 4 numbers.
And as I mentioned it on comment for _Nyro, I was really stupid that I attached the script to 6 objects, so that I got 6 times of the result!