A random number generator that orders numbers from small to large

I am new to JavaScript and I am trying to write a function that generates a number between 0 and 90 and returns that number to an HTML file. I am trying to order it small to large, this is my code, but it doesnt order it.

var timeStart = 0;

function timeGenerator(timeStart) {
    var time = Math.floor(Math.random() * 90 + 1);
    if (time > timeStart) {
        timeStart = time;
    } 
    return timeStart; 
}  
document.getElementById("Scorers").innerHTML += '<p>'+Scorers[Math.floor(Math.random() * 10)]+' '+timeGenerator(timeStart)+"'</p>";

      

+3


source to share


2 answers


Ok so I edited my answer, hope this code helps you:

var Players = ["Player1", "Player2", "Player3"];
var Scorers = [];

function newScore(player, time){
    tuple = [time, player];
    Scorers.push(tuple);
}

newScore(Players[0], parseInt(Math.floor(Math.random()*90+1)), 10);
newScore(Players[1], parseInt(Math.floor(Math.random()*90+1)), 10);
newScore(Players[2], parseInt(Math.floor(Math.random()*90+1)), 10);

// Order
Scorers.sort(function(current, next){ return current[0] - next[0];});

for (i=0; i < Scorers.length; i++){
    document.getElementById("Scorers").innerHTML += '<p>'+Scorers[i][1]+ ' - ' + Scorers[i][0] + '</p>';
}

      



Demo

+1


source


Your question is rather vague, but you can try this:

var timeStart = 0;
var output = [];
function timeGenerator(timeStart) {

    var time = Math.floor(Math.random() * 90 + 1);
    if (time > timeStart) {
        timeStart = time;
    } 
    output.push(timeStart); 
    output.sort();

;
    document.getElementById("Scorers").innerHTML = "</p>"+ output.toString() +"</p>";
}  

      



It stores the sorted numbers in an array, which is always re-printed with the element.

0


source







All Articles