Skip to content

Instantly share code, notes, and snippets.

@renatocassino
Last active August 11, 2018 22:52
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 renatocassino/7fa90f7cf369b593dfa0ef2e0470f4c5 to your computer and use it in GitHub Desktop.
Save renatocassino/7fa90f7cf369b593dfa0ef2e0470f4c5 to your computer and use it in GitHub Desktop.
2048-moveUpRecursion.js
/**
* @param line Array Old board array
* @param result New array with new state. Start empty
* @param lineWithoutZerosMemoized array list of numbers in line without 0
*/
const moveLineUpFirst = (line, result=[], lineWithoutZerosMemoized=null) => {
const currentIndex = result.length; // The size of result is equals the line index
if(line.length === currentIndex) return result; // if result are full, return
const lineWithoutZeros = lineWithoutZerosMemoized || line.filter((n)=>n > 0); // In first iterate, set, in next iterates keep the value
if (currentIndex >= lineWithoutZeros.length) { // If current iterate is over than numbers without 0
// Only add 0 in array result
return moveLineUpFirst(line, [...result, 0], lineWithoutZeros);
}
if (lineWithoutZeros[currentIndex] === lineWithoutZeros[currentIndex + 1]) { // If equals next number
const total = lineWithoutZeros[currentIndex] + lineWithoutZeros[currentIndex + 1]; // sum
// Add sum in result and remove the first number in lineWithoutZeros (because the blocks joined in one)
return moveLineUpFirst(line, [...result, total], lineWithoutZeros.slice(1));
}
// Add number in result and call again
const newNumber = lineWithoutZeros[currentIndex];
return moveLineUpFirst(line, [...result, newNumber], lineWithoutZeros);
};
const board = [
[2, 0, 4, 2],
[0, 0, 4, 4],
[2, 2, 2, 2],
[2, 16, 16, 0]
];
console.log(board.map(line => moveLineUpFirst(line)));
/**
[
[ 2, 4, 2, 0 ],
[ 8, 0, 0, 0 ],
[ 4, 4, 0, 0 ],
[ 2, 32, 0, 0 ]
]
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment