I'm trying to simplify/generalize a function foo_one
that traverses through a multidimensional array and sets all sub-array elements apart from the first one to have null
values.
I was given only the first function, for which I should then find more ways to generalize it to still accomplish the intended purpose of foo_one
.
Any suggestions would be highly appreciated.
I've already implemented 2 other variations of the function and I like to have more if possible.
var arr = [
[2, null, 2, null],
[2, null, 2, null],
[null, null, null, null],
[null, null, null, null]
];
function foo_one() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr.length - 1; x++) {
if (arr[x + 1][y] != null) {
if (arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
if (arr[x][y] == null) {
arr[x][y] = arr[x + 1][y];
arr[x + 1][y] = null;
}
}
}
}
}
function foo_two() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr.length - 1; x++) {
if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
}
}
}
function foo_three() {
for (let y = 0; y < arr.length - 1; y++) {
for (let x = 0; x < arr[y].length - 1; x++) {
if (arr[x + 1][y] != null && arr[x + 1][y] == arr[x][y]) {
arr[x][y] = arr[x][y] * 2;
arr[x + 1][y] = null;
}
}
}
}
// Output
[ [ 4, null, 4, null ],
[ null, null, null, null ],
[ null, null, null, null ],
[ null, null, null, null ] ]