Skip to content

Instantly share code, notes, and snippets.

@rajivnarayana
Created November 14, 2018 20:04
Show Gist options
  • Save rajivnarayana/a3ceadc2d1300e48fbfec921f0fd324c to your computer and use it in GitHub Desktop.
Save rajivnarayana/a3ceadc2d1300e48fbfec921f0fd324c to your computer and use it in GitHub Desktop.
A function that traverses a single array (row) of elements moving and matching merges to the beginning of array like the game 2048.
const tests = [
[[4, 4, 2, 4],[8, 2, 4, 0]],
[[4, 0, 0, 4],[8, 0, 0, 0]],
[[2, 4, 4, 0],[2, 8, 0, 0]],
[[4, 4, 4, 4],[8, 8, 0, 0]],
[[4, 4, 4, 0],[8, 4, 0, 0]],
[[4, 4, 0, 4],[8, 4, 0, 0]],
[[2, 4, 0, 4],[2, 8, 0, 0]],
[[2, 4, 8, 4],[2, 4, 8, 4]],
[[2, 4, 8, 16],[2, 4, 8, 16]],
[[4, 0, 0, 0],[4, 0, 0, 0]],
[[2, 4, 2, 4],[2, 4, 2, 4]],
];
const traverse = function(a) {
const [first, ...rest] = a;
if (rest.length == 0) {
return [first];
}
if (first == 0) {
return [...traverse([...rest]), 0];
}
const secondIndex = rest.findIndex(num => num>0);
if (secondIndex < 0) {
return [first , ...rest.map(_ => 0)];
}
if (first == rest[secondIndex]) {
return [2 * first, ...traverse([...rest.slice(secondIndex + 1), ...new Array(secondIndex+1).fill(0)])];
}
return [first, ...traverse([...rest])];
// Alternately
// return [first, ...traverse([...rest.slice(secondIndex), ...new Array(secondIndex).fill(0)])];
}
const match = (ar1, ar2) => ar1.every((ele, index) => ele == ar2[index]);
tests.forEach(([input, expected], index) => {
const result = traverse([...input]);
if (match(expected, result)) {
console.log(`Passed ${index + 1} ${input} ${result}`);
} else {
console.log(`Failed ${index + 1} ${input} ${result}`);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment