× {{alert.msg}} Never ask again
Get notified about new tutorials RECEIVE NEW TUTORIALS

Looping through a n-dimensional array

Asad Saeeduddin
Oct 08, 2015
<p>Visiting all elements in a multidimensional array is not difficult. You can simply do a flat iteration through the entire array with a single index. The tricky part is mapping this single index to the corresponding multidimensional coordinates.</p> <p>In general, given a matrix with size vector <code>D</code>, the <code>i</code>th single indexed element of this matrix has a coordinate vector <code>C_i</code>, such that:</p> <p><img src="http://i.stack.imgur.com/hwdS6.png" alt="enter image description here"></p> <p>For <code>0 &lt;= n &lt; size(D)</code>.</p> <p>Implementing this, the <code>IndexToCoordinates</code> method is:</p> <pre><code>static int[] IndexToCoordinates(int i, Array arr) { var dims = Enumerable.Range(0, arr.Rank) .Select(arr.GetLength) .ToArray(); Func&lt;int, int, int&gt; product = (i1, i2) =&gt; i1 * i2; return dims.Select((d, n) =&gt; (i/dims.Take(n).Aggregate(1, product))%d).ToArray(); } </code></pre> <p>Now, for example, if you wanted to visit every item in a multidimensional array and output its coordinates, you could do:</p> <pre><code>static void OutputAllArrayIndices(Array arr) { var i = 0; foreach (int item in arr) { var coords = IndexToCoordinates(i++, arr); Console.WriteLine(string.Join(", ", coords)); } } </code></pre> <p>Running <code>OutputAllArrayIndices(new int[3, 2, 4])</code> then produces:</p> <pre><code>0, 0, 0 1, 0, 0 2, 0, 0 3, 0, 0 0, 1, 0 1, 1, 0 2, 1, 0 3, 1, 0 0, 0, 1 1, 0, 1 2, 0, 1 3, 0, 1 0, 1, 1 1, 1, 1 2, 1, 1 3, 1, 1 0, 0, 2 1, 0, 2 2, 0, 2 3, 0, 2 0, 1, 2 1, 1, 2 2, 1, 2 3, 1, 2 </code></pre> <p>This tip was originally posted on <a href="http://stackoverflow.com/questions/28867327/Looping%20through%20a%20n-dimensional%20array/28868622">Stack Overflow</a>.</p>
comments powered by Disqus