Show array elements in random order

Asked

Viewed 964 times

2

I have a code that asks the user to inform the number of people, then I ask him to inform the name of people, only when it shows on the screen, he should bring it to me like this, follows below:

numeroPessoa = 4
nome = raphael
nome = gabi
nome = jorge
nome = alex

When displaying the name on the screen at the end of the code should be presented as follows:

nome = gabi
nome = alex
nome = raphael
nome = jorge

This way random, and not in the order that was stored in my vector. Follow code below:

<script>

    

function gerar(fim){
          
          return Math.floor(Math.random()* fim )+ 1;

        }
         
          numeroPessoas = window.prompt("Digite um numero de pessoas");
          fim = numeroPessoas;
           vetor = new Array ();
           for (i = 1 ; i <= numeroPessoas; i++){
            
                var nome = window.prompt("Digite o nome");
                vetor.push([i] +"º" + " -" + " " +  nome + " ");
                

           }
            
             for (j = 0; j < numeroPessoas; j++){
                   
                  k = gerar(numeroPessoas.length);

              
                    document.write(vetor[K] + "<br>" + "<hr>");
               
          

             }
        
          
    

 </script>

inserir a descrição da imagem aqui

2 answers

2

Look, I found the following problems:

  • Uppercase K in the array index
  • Add + 1 in the Random, this can access a non-existent array position
  • numeroPeople.length, it’s already a number, so you can’t access the lenght property
  • end = numeroPeople; you declare the variable, but the function takes as parameter

Correcting these points, the code worked, but there is the possibility of repeating the people in this created Random:

<script>

  function gerar(fim){
    //Remoção do + 1 para evitar acessar um índice inexistente do array
    return Math.floor(Math.random() * fim );
  }

  let numeroPessoas = window.prompt("Digite um numero de pessoas");
  let vetor = new Array();

  for (i = 1 ; i <= numeroPessoas; i++){  
    let nome = window.prompt("Digite o nome");
    vetor.push([i] +"º" + " -" + " " +  nome + " ");
  }

  for (j = 0; j < numeroPessoas; j++){
    k = gerar(numeroPessoas); // Ou usar o vetor.lenght
    document.write(vetor[k] + "<br>" + "<hr>");
  }

</script>

  • To avoid drawing the same, could make a array.slice() returning the person’s name

2

Analyzing

Your code has many errors and does not match what is proposed in the question, which can be defined in steps:

1. Collecting the data

2. Shuffling the data

3. Display the data

The first step your code managed to complete successfully, but the last two did not. The function gerar(fim) no utility. There was an error between declaring and using the variable k.

Solution

In my view the solution is to take advantage of what you did in the first step, collect the data and implement the other two steps: shuffle the data and display the data.

Shuffle the data

To shuffle an array you must use the Fisher-Yates scrambling algorithm. This algorithm was described in 1938 by Ronald Fisher and Frank Yates in their work Statistical Tables for Biological, agricultural and Medical research(Statistical tables for biological, agricultural and medical research).

Fisher-Yates scrambling is an algorithm that generates a random permutation of a finite sequence - in simple terms, the algorithm scrambles the sequence. The algorithm works as if it puts all the elements in a hat, it continually determines the next element by randomly taking an element of the hat until no element remains.

The algorithm produces unbiased permutation: all permutation is equally likely. The modern version of the algorithm is efficient: it takes time proportional to the number of shuffled items and shuffles them in place.

The algorithm is very simple:

- Para embaralhar uma matriz a[] de n elementos (índices 0..n-1):
    faça :i de n − 1 decrescer para 1 
      atribua :j ← inteiro aleatório tal que 0 ≤ j ≤ i
      trocar a[j] com a[i]
    fim faça

Display the data

To display the data I will use the method Console.log() that displays a message in the browser console allied to the method Array.Join() that joins all elements of an array into a string.

Answer

//Coleta de dados aproveitada e simplificada a partir do seu código
numeroPessoas = window.prompt("Digite um numero de pessoas");
var vetor = new Array();
for (i = 0 ; i < numeroPessoas; i++){            
      vetor.push(window.prompt("Digite o nome"));
}

//Exibição dos dados
console.log('Número de pressoas:' + vetor.length + "\n");
console.log('Entrada:' + vetor.join("-") + "\n");
console.log('Embaralhado:' + embaralhar(vetor).join("-") + "\n");

   
// Algoritmo de embaralhamento de Fisher–Yates
function embaralhar(array) {
  for (var i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
  }
  return array;
}

Browser other questions tagged

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