Home > Enterprise >  How to generate random numbers in the same line with Js?
How to generate random numbers in the same line with Js?

Time:01-28

I have an algorithm that simulates a lottery generating numbers from 1 to 50 and numbers from 1 to 10. For this, I'm using a Math function and a for loop to code this lottery.

My problem is to find a way for my result to come out in one line instead of new lines. I'll explain with some code:

for (let rand_num = 1; rand_num <= 5; rand_num  ) {
    console.log("Numbers")
    console.log(Math.floor(Math.random() * 50)   1);
}

for (let rand_star = 1; rand_star <= 2; rand_star  ) {
    console.log("Stars")
    console.log(Math.floor(Math.random() * 10)   1);
}

Output:

Numbers

10

Numbers

8...

Stars

2

Stars

7...

As this output takes up too much space I would like another alternative that leaves random values in the same line like this output example:
Output:

Numbers: 10 - 8 - 50 - 44 - 21

Stars: 2 - 7

CodePudding user response:

If you want to get it from loop, just make a string:

let result = "Numbers "
for (let rand_num = 1; rand_num <= 5; rand_num  ) {
  result  = Math.floor( Math.random() * 50  1)

}

console.log(result)

CodePudding user response:

You can always create a reusable function to generate the random numbers and place them into an array. Then return those numbers separated by your seperator.

function lotteryNumbers(max, total) {
  let nums = [];
  for (let x = 1; x <= total; x  ) {
    nums.push(Math.floor(Math.random() * max)   1);
  }
  return nums.join(" - ");
}

console.log("Numbers: "   lotteryNumbers(50, 5));
console.log("Stars: "   lotteryNumbers(10, 2));

  • Related