c# - How can i fill 2 dimensional array with unique random numbers -
how can fill 2 dimensional array unique random numbers (different numbers in row/colum)?
i have done 1 dimensional array:
class program { static void main(string[] args) { random r = new random(); int[] x = new int[10]; for(int = 0; < x.length; i++) { x[i] = r.next(9); for(int j = 0; j < i; j++) { if(x[i] == x[j]) { i--; break; } } } for(int = 0; < x.length; i++) { console.writeline(x[i]); } console.readkey(); } }
since don't want duplicates, using random
repeatedly until have 1 of each not best approach. theoretically, algorithm run very long time, if randomizer not provide desired values on.
since know values want, want them in random order, shuffle algorithm better approach. shuffle algorithm allow generate array of desired values , shuffle them them in random order.
the easiest way working multidimensional arrays, have desired values in one-dimensional array first, shuffle , convert array multidimensional array. however, it possible generalize shuffling algorithm work on multidimensional arrays.
an example of how code provided in referenced answers.
Comments
Post a Comment