Created
October 14, 2016 21:03
-
-
Save vdubyna/9f5f6e5b90a3c44b2b02224404b6672b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var execute = function () { | |
| var field = [ | |
| [{a: 1}, {a: 2}, {a: 3}, {a: 4}], | |
| [{b: 1}, {b: 2}, {b: 3}, {b: 4}], | |
| [{c: 1}, {c: 2}, {c: 3}, {c: 4}], | |
| [{d: 1}, {d: 2}, {d: 3}, {d: 4}] | |
| ]; | |
| var directions = { | |
| right: [0, 1], | |
| bottom: [1, 0], | |
| left: [0, -1], | |
| top: [-1, 0] | |
| }; | |
| var directionsOrder = ['right', 'bottom', 'left', 'top']; | |
| var currentAddress = [0,0]; | |
| var newAddress = []; | |
| var getNewAddress = function (currentAddress, directions, directionsOrder, currentDirection) { | |
| return [ | |
| currentAddress[0] + directions[directionsOrder[currentDirection]][0], | |
| currentAddress[1] + directions[directionsOrder[currentDirection]][1] | |
| ]; | |
| }; | |
| var visitCell = function (field, currentAddress, currentDirection) { | |
| // Print address | |
| console.log(field[currentAddress[0]][currentAddress[1]]); | |
| // mark cell as visited | |
| field[currentAddress[0]][currentAddress[1]] = 'VISITED'; | |
| newAddress = getNewAddress(currentAddress, directions, directionsOrder, currentDirection); | |
| // Check if newAddress does not exist, we change direction based on the direction order. | |
| if (typeof field[newAddress[0]] == 'undefined' | |
| || typeof field[newAddress[0]][newAddress[1]] == 'undefined' | |
| ) { | |
| currentDirection = (currentDirection === 3) ? 0 : currentDirection + 1; | |
| newAddress = getNewAddress(currentAddress, directions, directionsOrder, currentDirection); | |
| visitCell(field, newAddress, currentDirection); | |
| return; | |
| } | |
| if (field[newAddress[0]][newAddress[1]] == 'VISITED') { | |
| // If VISITED we change direction | |
| currentDirection = (currentDirection === 3) ? 0 : currentDirection + 1; | |
| newAddress = getNewAddress(currentAddress, directions, directionsOrder, currentDirection); | |
| // if new direction is visited we return, there is no unvisited cells; | |
| if (field[newAddress[0]][newAddress[1]] == 'VISITED') { | |
| return; | |
| } else { | |
| visitCell(field, newAddress, currentDirection); | |
| } | |
| } else { | |
| visitCell(field, newAddress, currentDirection) | |
| } | |
| }; | |
| visitCell(field, currentAddress, 0); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment