c# - Randomise an array of integers -
this question has answer here:
- randomize list<t> 16 answers
- is using random , orderby shuffle algorithm? 12 answers
can me find way randomize arrays? e.g.:
int[] arrayint = { 1, 2, 3, 4, 5, 6, 7 };
after randomizing, result should stored in array.
and when randomize again should compared values stored in second array, if value exist program must randomize again.
here's approach using enumerable.orderby
order input-array random variable. after new sequence generated it'll compared input array sequenceequal
:
public static t[] uniquerandomarray<t>(t[] input, random rnd) { if (input.length <= 1) throw new argumentexception("input array must have @ least 2 elements, otherwise output same.", "input"); ienumerable<t> rndseq; while (input.sequenceequal(rndseq = input.orderby(x => rnd.next()))); return rndseq.toarray(); }
this example-code generates 10 new arrays added list. ensured new array different previous one:
random rnd = new random(); list<int[]> randomarrays = new list<int[]>(); int[] arrayint1 = { 1, 2, 3, 4, 5, 6, 7 }; randomarrays.add(arrayint1); (int = 0; < 10; i++) { int[] lastarray = randomarrays[randomarrays.count - 1]; int[] randomarray = uniquerandomarray(lastarray, rnd); randomarrays.add(randomarray); }
Comments
Post a Comment