6

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

So far 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 make the loop actually generate random numbers as stated 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 
`.
Cœur
  • 37,241
  • 25
  • 195
  • 267
hannacreed
  • 639
  • 3
  • 15
  • 34

4 Answers4

5

You can do it in a more simply way:

The solution is to push the random generated number into one array and then use join method in order to join all elements of the array the string desired.

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(' '));
Mihai Alexandru-Ionut
  • 47,092
  • 13
  • 101
  • 128
2

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); 
Me.Name
  • 12,259
  • 3
  • 31
  • 48
1

print() is a function which goal is to print a document, you should use console.log() to display in console.

Put a boolean before your loop, for example var eightAppear = false

Your condition now look like do {... }while(!eightAppear)

Then inside your loop generate a random number between 0 and 9. Math.floor(Math.random()*10) Concat your string. If number is 8 change value of eightAppear to true

Since it seem to be an exercise, i'll let you code it, should not be hard now :)

Nolyurn
  • 568
  • 4
  • 17
1

Here is another way to accomplish this. Here I'm creating a variable i and storing the random number in it, then I create the while loop.

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

console.log(text);

Here is the same thing but as a do...while loop.

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