I want to make sure that in array elements values cant have the same generated numbers.
For example
A[0]=1, A[1]=4, A[2]=3, A[3]=9 element values cant be equivalent
for(var i: int=0;i<A.length;i++)
{
A*=Random.Range(1,11);//generates number for array element*
//algorithm that checks if there are equivalent numbers in array and of there //is, then generates element value so much times(loop) until there are no //equivalent elements in array.
- declare a new sortedlist for example of the type SortedList<int,int> mylist = new SortedList<int,int>();
- change your for cycle with a while loop
- in the loop use the 'ContainsKey' instruction to check if the new random number you get is already inside the list. If it isn't, you add the key and the index to the list.
- transform the list in an array at the end of the loop, simply cycling through all the keys.
Done.
problem is that im using js. cant translate all script to cs :( is there any alternative?
What you are looking for is a [Set][1]. Through Unity/Mono you have the [Dictionary][2] collection type available which will serve the purpose by using only the keys in your implementation (which is fast because dictionary keys are usually backed by a hash algorithm). Just check if the dictionary contains a key that is equal to the generated number. if yes, generate another one. if no, put it into your next array element and also into the dictionary.
Example (not tested):
// At the top of your script
import System.Collections.Generic;
// somewhere below
var values : Dictionary.<int,int> = new Dictionary.<int,int>();
var r : int;
for(var i: int=0;i<A.length;i++)
{
while(values.ContainsKey(r = Random.Range(1,11)));
values.Add(r, i); // this also tells you at which index the generated number is
A *= r;*
It sounds like what you want is what is sometimes called a ‘Knuth shuffle’; rather than generate values one by one and attempt to add them to your array if they are unique, you generate all of the unique values that you want, then permute them randomly with pairwise swaps. The technique is described here:
problem is that im using js. cant translate all script to cs :( is there any alternative?
– Sacristan_G