- Home /
Rolling random numbers
Lets say I have integers between 1 and 10. First time I chose randomly integer with Random.Range(1,10)
. Let's say it returns 8. Now I want to get number again from 1 to 10, but I want that it would not return 8 now. So basically I want that each time number is rolled, I want that it won't be rolled again on next roll. How it would be easiest to implement this?
Answer by el-pepi · Mar 15, 2015 at 02:32 AM
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class RandomNumber : MonoBehaviour {
List<int> numberList = new List<int>();
void Start () {
int numberAmmount = 10;
while(numberAmmount > 0){
numberList.Add(numberAmmount);
numberAmmount--;
}
}
int GetRandomNumber(){
if(numberList.Count == 0)
return -1; //there are no more numbers left
int i = Random.Range(0,numberList.Count);
int toReturn = numberList[i];
numberList.RemoveAt(i);
return toReturn;
}
}
Here you go, I didn't test this tho.
Answer by Eluate · Mar 14, 2015 at 11:48 PM
Just save the last rolled int as a variable
int oldInt = 0;
while (rolling)
{
int rolledint = Random.Range(1,10);
if (rolledint != oldInt)
{
Debug.log("Rolled: " + rolledint);
}
}
it would overwrite oldInt at second roll, i.e. if first roll oldInt becomes 8, at second roll it becomes 6 then at third roll there is again possibility to roll 8 :(
Answer by diego_prado · Nov 07, 2016 at 06:33 PM
Hi @chanfort
My solution was to make an array of the "valid numbers", and always ask a random for the position in that array. Check this code:
private static List<int> Generate(List<int> initialNumbers)
{
List<int> generatedNumbers = new List<int>();
Random rnd = new Random(DateTime.Now.Millisecond);
int position, nextNumber;
while (initialNumbers.Count > 0)
{
position = rnd.Next(initialNumbers.Count());
nextNumber = initialNumbers.ElementAt(position);
generatedNumbers.Add(nextNumber);
initialNumbers.Remove(nextNumber);
}
return generatedNumbers;
}
The function gets an array of the "valid numbers" and return and array "shuffled". This has been already used and tested with 1000 numbers.
Your answer
![](https://koobas.hobune.stream/wayback/20220613190151im_/https://answers.unity.com/themes/thub/images/avi.jpg)