I have a matrix consisting in 0s, 1s and an "X" and I'm trying to use the "forEach()" method in order to find the "X" and replace it with another value. How would I exactly do that?
let a=new Array
for(int i=0;i<=5;i++) {
a[i]=new Array
for(int j=0;j<=5;j++) {
a[i][j]=Math.round(Math.random())
}
}
a[3][2]="X" //the indexes are random values
for(int i=0;i<=5;i++) {
for(int j=0;i<=5;j++) {
if(a[i][j]=="X") {
a[i][j]="found"
break
}
}
}
let matrix1 = [
[0, 1, 0, 1, 1],
[1, 0, 1, 1, 1],
[0, 1, 1, 0, 0],
[1, 0, 1, 0, 1],
[0, 1, 1, 'x', 1]
];
matrix1
.forEach((element1, index1, array1) => {
element1.forEach((element2, index2, array2) => {
if(array1[index1][index2] == 'x') {
array1[index1][index2] = 'y';
}
});
});
There may be other (and better solutions), but this should work. But I would recommend to stay with the two nested-for-loops.
For the forEach approach two lambda-functions have to be created and when they are called a context-switch happens (not sure about that, might be optimized/removed by the javascript interpreter). So the memory-footprint might be slightly higher and the performance probably lower. But for a 5x5 matrix nothing of that is important.
Plain for loops are also much more readable - at least for me ;)
Instead of doing it with forEach, I would be using for-of loop.
let matrix = [
[0, 1, 0, "x", 1],
[1, 0, 1, 1, 1],
[0, "x", 1, 0, 0],
["x", 0, 1, 0, 1],
[0, 1, 1, 0, 1]
];
for (const [i, row] of matrix.entries()) {
for (const [j, element] of row.entries()) {
if (element === "x") {
matrix[i][j] = "Boom";
}
}
}
Final, output would be:
[
[0, 1, 0, "Boom", 1],
[1, 0, 1, 1, 1],
[0, "Boom", 1, 0, 0],
["Boom", 0, 1, 0, 1],
[0, 1, 1, 0, 1]
]