hannacreed hannacreed - 5 months ago 29
Javascript Question

Random Number in a do-while loop with if statement

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
`.

Answer Source

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(' '));