Last active
August 11, 2018 22:52
-
-
Save renatocassino/7fa90f7cf369b593dfa0ef2e0470f4c5 to your computer and use it in GitHub Desktop.
2048-moveUpRecursion.js
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
/** | |
* @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