I'm learning about the "The Fisher Yates shuffle" and came across an issue. The part of my code that I've highlighted and commented "This Work", "This Doesn't Work" is to shuffle the array. From my understanding of Javascript, the part that doesn't work should work. Can you explain to me why it doesn't work?
const array = [..."12345678"]
let arrayShuffle = function(arr){
for(let i = array.length - 1; i > 0; i--){
let randomNum = Math.floor(Math.random() * (i + 1))
let temp;
let currentPos = arr[i]
let randomPos = arr[randomNum]
/* This Work(it shuffled) \/ */
temp = arr[i]
arr[i] = arr[randomNum]
arr[randomNum] = temp
/* This Doesnt Work(Doesn't shuffle) \/ */
// temp = currentPos
// currentPos = randomPos
// randomPos = temp
}
return arr
}
let res = arrayShuffle(array)
console.log(res)
This does not work, because of currentPos = arr[i]
and randomPos = arr[randomNum]
. Both of these are copying the values in arr, not the acctual pointer. Therefore, when you change currentPos
or randomPos
you are just changing a copy of whats actually in the array.
Take for example,
let x == 5
let y == x
y = y+1
console.log(x)
console.log(y)
x = 5
y = 6
The same thing is going on here. when we let y = x, it is only copying the value in x, and it is not an actual reference back to x. Therefore when we change y, we are only changing y, leaving x unaffected.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments