Align different random numbers smaller to larger
Hi. I want to get four different random numbers that range 1 to 50, and align them smaller to bigger.
For example, if I get (45,20,1,18), align them to be (1,18,20,45).
My script is stacked at "random.range(1,51)". Could you please give me some advice?
Thank you in advance!
Answer by gjf · Jul 16, 2016 at 05:55 PM
that's called sorting. put them in a List
and then use listName.Sort();
Thank you for your help.
Sorting is what I was looking for! But, unfortunately my script doesn't work. I repost this with my script in the bellow link.
I'd really appreciate if you could check it! Thank you.
http://answers.unity3d.com/questions/1219159/sort-unique-random-numbers.html
Answer by tippi-co · Jul 18, 2016 at 09:51 AM
Thank you for the help! I'm trying it, but it's something wrong . I get 18 of random, but repeatable numbers and not sorted.
result{22.29.38.1.13.27.17.37.39.9.17.21.37.39.40.27.29.43}
This time,two 17 and 37.
Could you help me to check my script?
List<int> fulNumList = new List<int>();
List<int> pickedNumber = new List<int>();
void Start(){
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);
}
}