Reputation: 587
Let's say I have a 1D game grid like the following:
As an example, the cell south of 27 will be cell 35, and the cell south of 59 will be 3 (because of wrap-around). This can be implemented like so:
var s = spot = 59
var r = row length = 8
var b = board size = 64
var south = (s+r) mod b
Okay, now let's try to find the cell east of another. The cell east of 27 is 28, and the cell east of 31 is 24 (also because of wrap-around). The best I could come up with is this:
var s = spot = 31
var r = row length = 8
var lc = left column = Math.floor(s / 8) * 8
var east = lc + ((s - lc + 1) % 8)
This is considerably more complex, which makes me think I'm missing something obvious. Is there not a better way to do this?
Also, I haven't yet implemented, but I'd imagine finding the diagonal cells like north-east and south-east even more complex still.
For the purposes of this question please assume this is limited to 1D arrays. Also, I'd imagine there is a bit-wise solution that could be more elegant for board sizes that are a power of two, but preferably the solution would work for any board size.
Upvotes: 3
Views: 1780
Reputation: 587
Here's a list of different methods I found for calculating east (in Javascript):
east = s + 1 - (s + 1 & 7 ? 0 : 8)
east = s + 1 - ((s % 8) / 7 | 0) * 8
east = (s + 1) % 8 == 0 ? Math.floor(s / 8) * 8 : s + 1
east = (s & 0xFFF8) + ((s - (s & 0xFFF8) + 1) % 8)
lc = Math.floor(s / 8) * 8; east = lc + ((s - lc + 1) % 8)
Upvotes: 0
Reputation: 80287
east:
i + 1 - ((i mod 8) div 7) * 8
west:
(i - 1) + (((i - 1) mod 8) div 7) * 8
or
(i - 1) + (((i + 7) mod 8) div 7) * 8
to avoid potential problems with negative dividend modulo in some languages
Upvotes: 1