Skip to content

Instantly share code, notes, and snippets.

@renatocassino
Last active August 11, 2018 23:46
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/87a3fbf97a514ac9314bafce701c6387 to your computer and use it in GitHub Desktop.
Save renatocassino/87a3fbf97a514ac9314bafce701c6387 to your computer and use it in GitHub Desktop.
2048-moveUpTry2.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 moveLineUp = (line, results=[], lineWithoutZerosMemoized=null) => {
// line is used like a counter to add in results
if(line.length === 0) return results; // If line is empty, get out recursion
const lineWithoutZeros = lineWithoutZerosMemoized || line.filter((n)=>n > 0);
if (lineWithoutZeros.length === 0) {
return moveLineUp(line.slice(1), [...results, 0], []); // Add 0 and remove one in array
}
const [currentValue, ...tail] = lineWithoutZeros; // <----- Head and Tail
if(currentValue === lineWithoutZeros[1]) {
return moveLineUp(line.slice(1), [...results, currentValue + lineWithoutZeros[1]], lineWithoutZeros.slice(2)); // Remove 2 in lineWithoutZeros, because two blocks joined in one
}
return moveLineUp(line.slice(1), [...results, lineWithoutZeros[0]], tail); // Add number and slice line and lineWithoutZeros
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment