Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>My approach is to start with a 1-d array of unique numbers, which you can shuffle, and then slot into appropriate places in your real array.</p> <p>Here is the main function:</p> <pre><code>private static void Initialize(Array array) { var rank = array.Rank; var dimensionLengths = new List&lt;int&gt;(); var totalSize = 1; int[] arrayIndices = new int[rank]; for (var dimension = 0; dimension &lt; rank; dimension++) { var upperBound = array.GetLength(dimension); dimensionLengths.Add(upperBound); totalSize *= upperBound; } var singleArray = new int[totalSize]; for (int i = 0; i &lt; totalSize; i++) singleArray[i] = i; singleArray = Shuffle(singleArray); for (var i = 0; i &lt; singleArray.Length; i++) { var remainingIndex = i; for (var dimension = array.Rank - 1; dimension &gt;= 0; dimension--) { arrayIndices[dimension] = remainingIndex%dimensionLengths[dimension]; remainingIndex /= dimensionLengths[dimension]; } // Now, set the appropriate cell in your real array: array.SetValue(singleArray[i], arrayIndices); } } </code></pre> <p>The key in this example is the <code>array.SetValue(value, params int[] indices)</code> function. By building up the correct list of indices, you can use this function to set an arbitrary cell in your array.</p> <p>Here is the <code>Shuffle</code> function:</p> <pre><code>private static int[] Shuffle(int[] singleArray) { var random = new Random(); for (int i = singleArray.Length; i &gt; 1; i--) { // Pick random element to swap. int j = random.Next(i); // 0 &lt;= j &lt;= i-1 // Swap. int tmp = singleArray[j]; singleArray[j] = singleArray[i - 1]; singleArray[i - 1] = tmp; } return singleArray; } </code></pre> <p>And finally a demonstration of it in use:</p> <pre><code>var array1 = new int[2,3,5]; Initialize(array1); var array2 = new int[2,2,3,4]; Initialize(array2); </code></pre> <p>My strategy assigns sequential numbers to the original 1-d array to ensure uniqueness, but you can adopt a different strategy for this as you see fit.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload