5

I've got a int that I want to convert to 3 ints for the index of a 3d array, here's an example of what I'm on about.

byte[,,] array = new byte[XSize, YSize, ZSize];

int i = 0;

//other code

array[#,#,#] = cur;

//other code

I don't know how to get the correct numbers for the #,#,# from just i.

7
  • Which way do you want to loop through it? Commented Jul 3, 2012 at 17:58
  • 1
    Could you provide more information? Are you trying to iterate over all items? Or are you attempting to directly access a single element from a single lookup value? Commented Jul 3, 2012 at 17:58
  • My previous comment still holds: Can you provide an input and the expected output? Commented Jul 3, 2012 at 17:59
  • I think you are trying to map (0,0,0) to 0, (0,0,1) to 1 and so on. Is that what you want? Could you clarify your question? Commented Jul 3, 2012 at 17:59
  • 1
    @Lost Its better to improve previous question rather than posting new question..... Commented Jul 3, 2012 at 18:01

2 Answers 2

17

Supposing you want to iterate through Z, then Y, and then X. . .

int zDirection = i % zLength;
int yDirection = (i / zLength) % yLength;
int xDirection = i / (yLength * zLength); 
Sign up to request clarification or add additional context in comments.

Comments

4

You have to make an assumption about the orientation of the array-space. Assuming you are mapping the numbers with 0 corresponding to 0, 0, 0, and that you iterate z, then y, then x, the math is fairly simple:

int x;
int y;
int z;

if (i < XSize * YSize * ZSize)
{
    int zQuotient = Math.DivRem(i, ZSize, out z);
    int yQuotient = Math.DivRem(zQuotient, YSize, out y);
    x = yQuotient % XSize;
}

Note that this saves some redundant operations over BlackVegetable's solution. For a (3, 3, 3) matrix, this yields the set:

i (x, y, z)
0 (0, 0, 0)
1 (0, 0, 1)
2 (0, 0, 2)
3 (0, 1, 0)
4 (0, 1, 1)
5 (0, 1, 2)
6 (0, 2, 0)
7 (0, 2, 1)
8 (0, 2, 2)
9 (1, 0, 0)
10 (1, 0, 1)
11 (1, 0, 2)
12 (1, 1, 0)
13 (1, 1, 1)
14 (1, 1, 2)
15 (1, 2, 0)
16 (1, 2, 1)
17 (1, 2, 2)
18 (2, 0, 0)
19 (2, 0, 1)
20 (2, 0, 2)
21 (2, 1, 0)
22 (2, 1, 1)
23 (2, 1, 2)
24 (2, 2, 0)
25 (2, 2, 1)
26 (2, 2, 2)

Also, this is reversible with i = z + y * ZSize + x * ZSize * YSize.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.