I am diving into TypeScript and just tackled my first slice() method. My understanding is that the slice() method is supposed to create a copy of an array. Here's a snippet of the code:
class ChapterOne {
// Gauss Jordan Elimination
// Notes: Only solve system of linear equation with one solution
static gaussJordanElim( linsys : number[][] ) {
const numOfEquation = linsys.length
const numOfUnknown = linsys[0].length - 1
if (numOfUnknown > numOfEquation) return 'This System of Linear Equation either have no solution or have infinite solutions'
// I slice it here.
const input = linsys.slice()
const length = input.length
// pointer = i, row to operate = j, column to operate = k
for (let i = 0; i < length; i += 1) {
if (input[i][i] === 0) return 'Mathematical Error! Cannot divide by zero'
for (let j = 0; j < length; j += 1) {
if (i !== j) {
const ratio = input[j][i] / input[i][i]
for (let k = 0; k < length + 1; k += 1) {
input[j][k] = input[j][k] - ratio * input[i][k]
}
}
}
}
// I Checked it here
console.log(input)
console.log(linsys)
const output = input.map((row, pointer) => row[length] / row[pointer])
return output
}
}
In essence, I created a duplicate of the original array, made various alterations to the duplicate without affecting the original, but noticed changes in both arrays when logged. Can someone shed light on why this is happening?
The primary objective is to clone the initial array, modify the cloned version, and preserve the original intact.