How can I generate 500 Numbers between 1 and 50 using javascript and without using arrays only loops (for)? I have written the below code but it's not generating any number and i want to print a histogram of stars that represent the percentage of numbers in each range without using an array
for (let i = 0; i < 500, i )
var temp = Math.floor((Math.random() * 50) 1);
let bin1 = 0;
let bin2 = 0;
let bin3 = 0;
let bin4 = 0;
let bin5 = 0;
if(temp >= 1 && temp < 11){
bin1 ;
document.write(bin1 " numbers are randomly generated between 01 - 10.<br>");
}
else if(temp >= 11 && temp < 21){
bin2 ;
document.write(bin2 " numbers are randomly generated between 11 - 20.<br>");
}
else if(temp >= 21 && temp < 31){
bin3 ;
document.write(bin3 " numbers are randomly generated between 21 - 30.<br>");
}
else if(temp >= 31 && temp < 41){
bin4 ;
document.write(bin4 " numbers are randomly generated between 31 - 40.<br>");
}
else if(temp >= 41 && temp < 51){
bin5 ;
document.write(bin5 " numbers are randomly generated between 41 - 50.<br>");
}
document.write("Histogram of stars as a percentage of the number of values are displayed below: <br>");
for(let x = 0; x < bin1*100/500; x ){
document.write("01 - 10: ");
document.write("*");
}
for(let x = 0; x < bin2*100/500; x ){
document.write("11 - 20: ");
document.write("*");
}
for(let x = 0; x < bin3*100/500; x ){
document.write("21 - 30: ");
document.write("*");
}
for(let x = 0; x < bin4*100/500; x ){
document.write("31 - 40: ");
document.write("*");
}
for(let x = 0; x < bin5*100/500; x ){
document.write("41 - 50: ");
document.write("*");
}
CodePudding user response:
There are some problems with the solution you developed:
- Expressions in the
for
loop;
should be separated from each other using character. - The
temp
variable only stores the last random number you generated.
The generate()
method in the solution below adds counter
numbers to an array.
function generate(array, counter) {
for (let i = 0 ; i < counter ; i )
array.push(Math.floor((Math.random() * 50) 1));
}
var array = [];
generate(array, 500);
console.log(array);
CodePudding user response:
The simple way to do.
The below for loop will help in generating 500 number between 1 and 50, without array.
the Javascript code.
for(i=0; i<500; i )
{
document.write( Math.floor((Math.random() * 50) 1) ," ");
}