Interview question. Do you know the answer? Is it too tough?
I've written 2 books in my life and while writing my 2nd book a question popped into my head out of nowhere and consumed me for the better part of an hour or so. The book was a "cookbook" and so I had to think of problems and then give the solution. Here's the question:
Let's say you had a multidimensional array. For the purposes of the discussion, let's say it's int[,,] arr1 = new int[3,3,3]; If I were to write this array out, I would have something similar to the following (the numbers I'm writing out let's say are the actual values in that array):
1 2 3 10 11 12 19 20 21
mdArray = 4 5 6 13 14 15 22 23 24
7 8 9 16 17 18 25 26 27
If I give you a single integer representing the index of an item in that array if that array were flattened, return the dimension indicies that value is at in the original multidimensional array. In other words, if we flatten out the array represented above to:
flatArray = 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
and I told you to return the indices of the value whose flattened array index is 12 (value would be the #13 above since it's at flatArray) you would return the mdArray indices [1,1,0]. If I gave you a flat index value of 1, you would return [0,0,1] which is where the value #2 shows up in the multidimensional array. As a starter, here's the function declaration:
int GetDimensionalIndices( int flatIndex, Array mdArray )
Couple of things to note here:
1. It doesn't have to a 3x3x3 array. It could be a 2x3x4 or a 4x3x2x2 or some other multidimensional array.
2. The Array class has some methods which may help you.
There you go. Reply with an answer or a comment along the lines of "you'd ask that on an interview. You crazy?" or "That's a good interview question".