Generate 7 random dozens using javascript and loop for? How to do?

Asked

Viewed 261 times

-1

This is my code:

function gerarDezenas() {

   var dezenas = ["d1","d2","d3","d4","d5","d6"];

   for (var i = 0; i < dezenas.length; i++) {

                 Math.random()*60
   dezenas[i] = Math.round(Math.random() * 60 +1); // isso é correto?

    console.log(dezenas) ou return... (??);
}
  
}

I couldn’t print anything.

also can’t understand when a code needs to have Return or not.

4 answers

2

It would probably be better to write like this: (I’m assuming you want to generate dozens like in a lottery game)

function gerarDezenas(numDezenas) {
    var dezenas = [];
    for (var i = 0; i < numDezenas; i++) {
        dezenas[i] = Math.floor(Math.random() * 100);
    }
    return dezenas;
}
console.log(gerarDezenas(7));

What has been modified?

  • The number of tens became a function parameter and not a "hardcoded" size within it. (This still brings low-level performance benefits as the array type does not change, but this is another conversation.)
  • I removed the expression Math.random()*60 that was alone there, requiring processing, but making no contribution to its algorithm.
  • I multiplied the random per 100 to have tens above 60 because I believe the right thing is to have all the dozens. If you don’t go back to 60.
  • I used floor instead of round to have numbers between 0 and 99 with equal probability instead of 0 to 100 where the extremes have the half the probability of qq other number. Read the definition of these methods and you will say "Yes! Of course!"
  • I removed the +1 to catch the 0. If you want to 1 to 100, put it back. (I don’t understand gambling)
  • I took the console.log() of the function so that it can be used for other purposes, not just generate and print on the console. This is good practice. Functions must stick to a specific action.
  • I put the return so that this function is able to deliver the result of its work to other functions for various purposes, which this function does not need and should not know.
  • Outside the function I logged, already passing the output of the generating function as argument of this log. The idea is exactly the same as the thematic classes you had in high school "Gof of x" = "g(f(x))"

There is still a catch: it is possible that the array returned by the function has repeated numbers. But this is already another conversation...

1

Somewhere in your code you invoked the function gerarDezenas()? For the behavior of a function to be executed, it is necessary that you invoke it. For this we write the function name and a pair of parentheses at the end.

// Invocando função
gerarDezenas();

Another tip is about indentation. Whenever you open keys, remember to indent the code that is inside the keys in another level. That is, when you declare a function, a conditional, a bond... as you open new structures you enter further, improving understanding. It’s easier to see that that block belongs to that structure. Your code with the correct indentation would look like this:

function gerarDezenas() {

   var dezenas = ["d1","d2","d3","d4","d5","d6"];

   for (var i = 0; i < dezenas.length; i++) {
       dezenas[i] = Math.round(Math.random() * 60 +1); // isso é correto?
       console.log(dezenas);
   }
}

Now about the code itself. The function Math.random() generates a number between 0 and 1, exclusive to 1, that is, up to 0.9999... (infinity nines). So if you take this and multiply it by 60, you will get a number between 0 and 59,9999... If you use only the Math.round() on top of that, without that +1, it would generate a number between 0 and 60. As you added 1, it would result between 1 and 61.

Also note that you are doing console.log(dezenas)

This will print your entire dozens list, will have the following output: ['d1', 'd2', ..., 'd6' ]

I believe what you wanted to do was to print the ith element of the list of dozens, that is, console.log(dezenas[i])

That will print a different string with each loop iteration.

Finally, whether a function returns or not (void function) depends on the type of behavior you expect from it. If you want the function to produce some result, surely it will have return. If you just want her to perform an action, or cause a side effect, it will be void. Its function, for example, could be done in both ways:

  • Returning a list of random dozens.
  • Printing a list of random dozens.

0


Follows the functional code.

gerarDezenas();

function gerarDezenas() {
   var dezenas = ["d1","d2","d3","d4","d5","d6"];

   for (var i = 0; i < dezenas.length; i++) {
        Math.random()*60
        dezenas[i] = Math.round(Math.random() * 60 + 1);
        console.log(dezenas[i]);
    }
}

In this case, the Return serves for when you want to have the return of the function, to save in some variable, and use later.:

 console.log(gerarDezenas());

    function gerarDezenas() {
       var dezenas = ["d1","d2","d3","d4","d5","d6"];

       for (var i = 0; i < dezenas.length; i++) {
            Math.random()*60
            dezenas[i] = Math.round(Math.random() * 60 + 1);
        }
        return dezenas;
    }

0

Generate 7 random dozens using javascript and loop for? How to do?

//numero de dezenas
const ARRAY_7DEZENAS = 7;
const randomArray = [];
for(let i = 0; i<ARRAY_7DEZENAS; i++) {randomArray.push(Math.floor(Math.random() * 100))};

    //separados por traço
    console.log(randomArray.join( '-' ));
    //array
    console.log(randomArray);

If you want to generate 7 numbers unique random in javascript you need to create an object, in this case you can use an array, which contains all possible numbers that may appear, called n. Then you can use a while loop to continue choosing numbers from that array and adding by the push() method and by the splice() method removing that specific number from the matrix in each iteration. You will understand better by observing the comments in the code.

function gerarDezenas() {
  // para armazenar as 7 dezenas 
  var escolha = [];
  
  //para armazenar todas as dezenas de 0 a n
  var arrayNumeros = [];

  // n é o valor máximo que pode aparecer entre os 7 numeros
  n=100;
  
  for ( var i = 0; i < n; i++ ) { 
    // Armazenando os numeros de 0 a 100
    arrayNumeros.push(i);
  }

  while (escolha.length < 7){
     var indiceAleatorio = Math.floor(Math.random() * arrayNumeros.length);
     
     //adicionando um numero no array escolha a ser apresentado
     escolha.push(arrayNumeros[indiceAleatorio]);
     
     // retirando o numero do array
     arrayNumeros.splice(indiceAleatorio, 1);
  }

  console.log(escolha);
}
gerarDezenas();

Browser other questions tagged

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