0

I am trying to run an Javascript algorithm to pick an array and reorder its elements randomly.

For this I need to swap array elements positions. Following this page I tried to do this by 2 different ways:

  1. Temp variable
A = [1,2,3,4,5]
temp = A[2]
A[2] = A[4]
A[4] = temp
console.log(A)
//Output: [1, 2, 5, 4, 3]
  1. Array Destructuring Assignment:
A = [1,2,3,4,5];
[A[2],A[4]] = [A[4],A[2]]
console.log(A)
//Output: [1, 2, 5, 4, 3]

Both ways worked properly when tried alone.

But implementing in my algorithm, only the first worked

  1. Temp variable
function reorder(A) {
    for (let i = A.length; i > 0; i--) {
        randomIndex = Math.floor(Math.random() * i)
        temp = A[randomIndex]
        A[randomIndex] = A[i - 1]
        A[i - 1] = temp
    }
}

A = [1, 2, 3, 4, 5]
reorder(A)
console.log(A)
//Output: Random order
  1. Array Destructuring Assignment:
function reorder(A) {
    for (let i = A.length; i > 0; i--) {
        randomIndex = Math.floor(Math.random() * i)
        [A[randomIndex], A[i-1]] = [A[i-1], A[randomIndex]]
    }
}
A = [1,2,3,4,5]
reorder(A)
console.log(A)
//Output: [1,2,3,4,5]

What is the explanation for this behavior?

pilchard
  • 12,414
  • 5
  • 11
  • 23
  • 4
    working as expected for me. (don't forget to declare your variables and you'll need semicolons in the destructuring example.) [jsfiddle](https://jsfiddle.net/0rkzL85a/) – pilchard Feb 02 '23 at 14:27
  • @pilchard here is an example where the output is always [1,2,3,4,5] https://onecompiler.com/javascript/3ywqyt86y – Rafael Leite Feb 02 '23 at 14:30
  • 1
    It's your missing semicolon. `...random() * i)` -> `...random() * i);` but also declare `randomIndex` to avoid using a global `let randomIndex...` – pilchard Feb 02 '23 at 14:31
  • Thanks! I am not used to put semicolons. I will read about to understand when it is mandotory. – Rafael Leite Feb 02 '23 at 14:36
  • 2
    Not declaring your variables is also a very bad habit... – Mister Jojo Feb 02 '23 at 14:40
  • 2
    *"I will read bout to understand when it is mandatory"*: it is much better practice to **always** add them at the end of a statement. Otherwise you leave it to this automatic semicolon insertion algorithm, giving you surprises like this. Take control and always use semicolons to separate your statements. – trincot Feb 02 '23 at 14:56

0 Answers0