Skip to content

Instantly share code, notes, and snippets.

@Daymannovaes
Created May 30, 2017 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Daymannovaes/05366cb5fba7a879911110db5354e336 to your computer and use it in GitHub Desktop.
Save Daymannovaes/05366cb5fba7a879911110db5354e336 to your computer and use it in GitHub Desktop.
// (x, y)
let stepActionByType = {
'down': [0, 1],
'left down': [-1, 1],
'left up': [-1, 0],
'up': [0, -1],
'right up': [1, -1],
'right down': [1, 0]
};
let stepTypeOrder = [
// 'down',
'left down',
'left up',
'up',
'right up',
'right down',
'down'
];
function stepsByRoundNumber(roundNumber) {
if(roundNumber === 1) return [];
let nMinus1 = roundNumber - 1;
let nMinus2 = roundNumber - 2;
return [
// 1 // down
nMinus2, // left down
nMinus1, // left up
nMinus1, // up
nMinus1, // right up
nMinus1, // right down
nMinus1 // down
];
}
function roundSize(roundNumber) {
if(roundNumber === 1) return 0;
return 6 + 6 * (roundNumber - 2);
}
function countNumberOfRounds(numberOfSteps) {
let countSteps = 1;
let countRounds = 0;
while(countSteps < numberOfSteps) {
countRounds++;
countSteps += roundSize(countRounds);
}
return countRounds;
}
// if numberOfSteps is higher than roundSize, roundSize will be considered instead
function walkMajaInRound(majaCoord, roundNumber, numberOfSteps) {
if(roundNumber === 1) return majaCoord;
if(numberOfSteps <= 0) return majaCoord;
let stepsByType = stepsByRoundNumber(roundNumber);
for(let i = 0; i < 6; i++) {
let stepType = stepTypeOrder[i];
for(let j = 0; j < stepsByType[i]; j++) {
majaCoord[0] += stepActionByType[stepType][0];
majaCoord[1] += stepActionByType[stepType][1];
numberOfSteps--;
if(numberOfSteps <= 0) return majaCoord;
}
}
return majaCoord;
}
function walkMaja(numberOfSteps) {
let majaCoord = [0, 0];
let rounds = countNumberOfRounds(numberOfSteps);
numberOfSteps--;
for(let i = 1; i <= rounds; i++) {
let stepsInRound = roundSize(i);
majaCoord = walkMajaInRound(majaCoord, i, numberOfSteps);
numberOfSteps -= (!stepsInRound ? 0 : stepsInRound - 1);
if(numberOfSteps > 0) {
majaCoord[0] += stepActionByType['down'][0];
majaCoord[1] += stepActionByType['down'][1];
numberOfSteps--;
} else return majaCoord;
}
return majaCoord;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment