 FlukeLogic
 Joined: 17 Nov 2008  Posts: 8  :   Items 

Posted: Wed Feb 24, 2010 4:12 am Post subject: Yet another mapping question 


how to map 3x3 boxes from an 81 element array?
This question was asked in another thread, and a formula provided, but what I went on to do was play around and see if the mapping formula would work for a 4x4, 9x9 or 16x16 (basically N*N where N is a square number) grid, and it does. Here is the formula in a C++ nested for loop, originally posted by angusj and modified by me (not to pat myself on the back because I'm sure others have figured this as well):
Code: 
for (box = 0; box < N; box++)
{
for (cell = 0; cell < N; cell++)
{
boxes[box][cell] = &grid[(box/sqrt(N))*(sqrt(N)*N)+(box%(int)sqrt(N))*sqrt(N)+(cell/sqrt(N)*N+(cell%(int)sqrt(N))];
}
}

Now, in my mind this shouldn't work according to order of operations  I even plugged the formula into google and it gave the same results I came up with on paper. Yet, it works when coded (using C++ with GNU GCC compiler).
This might be a better question for a C++ forum than here, but... can someone explain to me why this works? For example, for a 9x9 grid, here is the formula, assuming we want box 1 cell 1:
Code: 
boxes[1][1] = &grid[(1/3)*27+(1%3)*3+(1/3)*9+(1%3)];

Now to me (and google), that equals element 16  yet the compiler shows element 4 which is the correct element in the array... I mean, I guess if it works I won't complain but, wtf?
::confused:: 
