Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Traverse a Hexagon

Tags:

javascript

I can easily traverse the following from left to right, but I'm having a lot of trouble (2 days in, and no progress) getting a formula to traverse it from top right & bottom right.

enter image description here

Basically, I'm looking for a formula which can retrieve the following values:

let topRight = [
    [ h[2][4], h[3][3], h[4][2] ],
    [ h[1][3], h[2][3], h[3][2], h[4][1] ],
    [ h[0][2], h[1][2], h[2][2], h[3][1], h[4][0] ],
    [ h[0][1], h[1][1], h[2][1], h[3][0] ],
    [ h[0][0], h[1][0], h[2][0] ]
]

let bottomRight = [
    [ h[2][4], h[1][3], h[0][2] ],
    [ h[3][3], h[2][3], h[1][2], h[0][1] ],
    [ h[4][2], h[3][2], h[2][2], h[1][1], h[0][0] ],
    [ h[4][1], h[3][1], h[2][1], h[1][0] ],
    [ h[4][0], h[3][0], h[2][0] ]
]

The only part that I could get working was the topRight x value:

function hexagonArraySize(row) {
  if (row < this.size) {
    return (this.size + row)
  } else {
    return (this.size * 2 - (row % this.size) - 2)
  }
}

for (var i = 0, l = this.size * 2 - 1, j = l % size; i < l; ++i, ++j) {
  this.h[j] = new Array(this.hexagonArraySize(i)).fill().map((_, b) => {
    let x = (i > Math.floor(this.size / 2)) ? b : b + (this.size - i - 1)
    let y = 0 // didn't found the formula for this one...
  }, []).join("")
}

I made a fiddle available here: https://jsfiddle.net/0qwf8m1p/12/

There still is topRight y, bottomRight x & y to be found.

like image 972
joaumg Avatar asked Feb 03 '18 02:02

joaumg


1 Answers

Ok, so you worked out topRight x coordinate.

Both topRight and bottomRight y coordinates have the same equation:

  • You start with (size - 1) * 2
  • First value always equals (size - 1) * 2 - i) (where i is the sequence index)
  • Then you repeat first value i times, but at most size times

This wraps up to the following formula:

let y = (size - 1) * 2 - i - Math.max(0, b - Math.min(i, size - 1))
        |                  |                                      |
        |    first value   |      repeat at most size times       |

Next, you have to calculate x value for bottomRight. You have two cases here:

  • If i is less than size / 2 then value equals sequence length - b (item index)
  • Otherwise value equals (size - 1) * 2 - b

This wraps up to the following formula:

let x = (i > Math.floor(size / 2)) ? (size - 1) * 2 - b : hexagonArraySize(i) - b - 1
        |                          |                    |
        |       check index        |     second half    |          first half

Working fiddle here

like image 94
pwolaq Avatar answered Oct 05 '22 02:10

pwolaq