Does the shuffling function have traps not easily perceived?

Asked

Viewed 88 times

0

The function shuffle receives as input a array and the shuffle.

// 
function shuffle(a) {
 // atribui a variável n a quantidades de elementos da array a.
 n = a.length;
 // Percorre a array a da posição 0 até a ultima posição.
 for (var i = 0; i < n; i++) {
 //Sorteia uma posição aleatória entre i e n−1 e atribui para a variável swap
 swap = i + Math.floor(Math.random() * (n - i - 1));
 // Troca os valores das posições i e swap da array a.
 var aux = a[i];
 a[i] = a[swap];
 a[swap] = aux;
 }
}
var array = [5, 3, 1, 4, 2];
if (shuffle(array)) console.log(array);

There are potential pitfalls (pitfalls) in the above function? If YES what is it or what are they? Comment on the answer.

I had it executed and it didn’t work.

  • What is your question in response to the exercise?

  • tried to run and failed and did not understand the function functioning

  • Your if is preventing you from showing the output. Take out the if and run the direct function. So try to understand how it works and what the potential pitfalls might be.

  • @Albertoverzemiassiborguesani Has the answer solved your question? Do you think you can accept it? See [tour] if you don’t know how you do it. This would help a lot to indicate that the solution was useful for you. You can also vote on any question or answer you find useful on the entire site (when you have 15 points).

1 answer

2

Not in general, in particular we can not say because we do not know what you want, if it solves what you need. This algorithm even has a name, it’s called Fisher-Yates, and it’s the most used for scrambling data. How to be seen in another answer (a more complete one that leads to the analysis of alternatives).

The only bad thing about the function is that it does not declare the variables locally with var or let (one of them yes, so the code is strange for being inconsistent), not stating so the variable becomes global and there will have complicated traps to solve. If you run only this, it is not a problem, if you have other parts of code these variables may be confused with others, it may not be a problem there but it will create problems in other parts, depending on how they are written.

The function itself is correct, her call is quite wrong and makes no sense. The if has no function there and are walking to print an object and not the helmets of array which seems to be what you want.

function shuffle(a) {
    let n = a.length;
    for (let i = 0; i < n; i++) {
        let swap = i + Math.floor(Math.random() * (n - i - 1));
        let aux = a[i];
        a[i] = a[swap];
        a[swap] = aux;
    }
}

let array = [5, 3, 1, 4, 2];
shuffle(array);
for (let i = 0; i < array.length; i++) console.log(array[i]);

I put in the Github for future reference.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.