how to randomly generate number with out using a number twice
I am trying to randomly Generate number 0-9 without using a number twice Anyone have any idea how to do so heres the code i know why this code will not work but is there a algorithm that i can use or somthing :
public void GenerateRandomColor () { for(int i = 0;i <= 16;i++) { int randomColorIndex = Random.Range(0,8); colorPanels[i].GetComponent().material.color = colors[randomColorIndex]; colorPanels [i].GetComponent ().material.SetColor("_EmissionColor",colors[randomColorIndex]); tempColor = colors[randomColorIndex]; } }
You can store the randomColorIndex in an List and then check if it's been used.
public List<int> colorsUsed;
public void GenerateRandomColor ()
{
for(int i = 0;i <= 16;i++) // maybe change this to a while(colorsUsed.count < 8)
{
int randomColorIndex = Random.Range(0,8);
if(colorsUsed.Contains(randomColorIndex) continue; //this skips the loop and keeps running until it finds an Color(int) that has not been used
colorsUsed.Add(randomColorIndex);
colorPanels[i].GetComponent().material.color = colors[randomColorIndex];
colorPanels [i].GetComponent ().material.SetColor("_EmissionColor",colors[randomColorIndex]); tempColor = colors[randomColorIndex];
}
}
Answer by Momo26 · Sep 10, 2015 at 08:46 PM
Its ok i figured it out thanks for helping i used the Fisher-Yates shuffle algorithm that seem to do the trick.
heres a link to the algorithm : http://www.dotnetperls.com/fisher-yates-shuffle
Answer by hexagonius · Sep 07, 2015 at 09:15 PM
I think it's easier to fill a list with numbers and randomly pick one, then remove it.