Random number in do-while loop with if statement

I am trying to create a random number generator that generates a string of numbers from 1 to 9, and if it generates 8, it should display the last 8 and then stop generating.

While it prints 1 2 3 4 5 6 7 8, but it does not generate a random string of numbers, so I need to know how to get the loop to generate random numbers as above, thanks for any help!

Javascript

// 5. BONUS CHALLENGE: Write a while loop that builds a string of random integers // between 0 and 9. Stop building the string when the number 8 comes up. // Be sure that 8 does print as the last character. The resulting string // will be a random length. print('5th Loop:'); text = ''; // Write 5th loop here: function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; } i = 0; do { i += 1; if (i >= 9) { break; } text += i + ' '; } while (i <= 9); print(text); // Should print something like `4 7 2 9 8 `, or `9 0 8 ` or `8 `. 
+6
source share
4 answers

You can make it easier:

The solution is to push randomly generated number into one array, and then use the join method to combine all the elements of the array required for the string.

 function getRandomNumber( upper ) { var num = Math.floor(Math.random() * upper) + 1; return num; } var array = []; do { random = getRandomNumber(9); array.push(random); } while(random != 8) console.log(array.join(' ')); 
+4
source

print () is a function whose purpose is to print a document, you must use console.log () to display it on the console.

Put a boolean in front of your loop, for example var eightAppear = false

Your state now looks like do {... }while(!eightAppear)

Then, a random number from 0 to 9 is generated inside your loop. Math.floor(Math.random()*10) your string. If the number is 8 change values ​​from eightAppear to true

Since this seems to be an exercise, I will let you code it, now should not be difficult :)

+1
source

Not because it's better, but because we can (and I like generators :)), an alternative with an iterator function (ES6 required):

 function* getRandomNumbers() { for(let num;num !==8;){ num = Math.floor((Math.random() * 9) + 1); yield num; } } let text= [...getRandomNumbers()].join(' '); console.log(text); 
+1
source

Here is another way to do it. Here I create a variable I and store a random number in it, then create a while loop.

 i = Math.floor(Math.random() * 10) while (i !== 8) { text += i + ' '; i = Math.floor(Math.random() * 10) } text += i; console.log(text); 

It’s the same here, but how to do ... for now a loop.

 i = Math.floor(Math.random() * 10) do { text += i + ' '; i = Math.floor(Math.random() * 10) } while (i !== 8) text += i; console.log(text); 
0
source

Source: https://habr.com/ru/post/1270964/


All Articles