I have created an array which displays random instructions .
But it still has a chance to duplicate values.
Can you tell me which part is wrong yet.
public function random_array(){
var i:int;
var j:int;
var arr = new Array();
arr.length = 79;
for(i = 1;i<80;i++){
var r:int;
r = Random.Range(1,80);
// Debug.Log("Run1");
for(j = 1; j < i;j++){
if(arr[j] == r ){
r = Random.Range(1,80);
// Debug.Log("Run2");
}
}
arr[i] = r;
Debug.Log("Random : "+r);
}
}
If array size equals possible number count, you can generate array of following numbers (1…80) and permutate it.
Otherwise create list with all possible numbers and random indices from it:
var possibleValues = new Array();
// TODO; insert all possible values into array
var array = new Array();
array.length = 79;
for(i = 1; i < 80; i++)
{
var index = Random.Range(0, possibleValues.length);
array[i] = possibleValues[index];
possibleValues = possibleValues.splice(index, 1);
}
Just to note that most of the solutions provided above apply only to the “tight” set. Meaning n random non-repeating numbers in a range of n numbers. They don’t allow gaps between numbers. If I need to generate a 100 random non-repeating numbers in a range from 1 to 10000 then looks like most of the solutions fail. Correct me if I’m wrong but the only solution that works involves HashSet?