Reputation: 51
If i pass array in Math.abs() I cannot understand why it returns -3, why my value is changing from positive to negative
let test1 = [2, 3, 3, 1, 5, 2]
let test2 = [2, 4, 3, 5, 1]
function firstDuplicate(a) {
for (let i of a) {
console.log(i);
let posi = Math.abs(i) - 1;
//console.log(posi);
}
}
console.log(firstDuplicate(test1))
console.log(firstDuplicate(test2))
and I don't understand how Math.abs is working, real code is below
function firstDuplicate(a) {
for (let i of a) {
let posi = Math.abs(i) - 1
if (a[posi] < 0) return posi + 1
a[posi] = a[posi] * -1
}
return -1
}
Upvotes: 0
Views: 1379
Reputation: 480
Your code has some flaws.
for (let i of a) {
let posi = Math.abs(i) - 1
if (a[posi] < 0) return posi + 1
a[posi] = a[posi] * -1
}
Lets step through this, step by step with an example:
a[posi] will now get the value from the array at index 1 which is 3 (in array test1)
if (a[posi] < 0) return posi + 1 this will never return unless there is a negative number or 0 somewhere in your data (Math.abs(0) - 1 === -1).
a[posi] = a[posi] * -1 Now you change the value in your array. In our example: a[1] = a[1] * -1. This will leave the array in the following state: [2, -3, 3, 1, 5, 2]
I hope that this helps you to understand your own code. Maybe google for a solution on "how to find first duplicate in aray" and just copy that.
Upvotes: 1
Reputation: 361
Math.abs() returns absolute value of number. But u re multiplying your absolute value by negative 1. thats why you get negative value
a[posi] = a[posi] * -1
Upvotes: 2