Lottery Random Number Generator

What I'm trying to do is generate 6 random numbers, five in the range of 1-45 and one in the range of 1-25 for the Greek lottery (Tzoker). The first 5 numbers must be unique. By clicking the button, I want to add these numbers to the div using jQuery (I have working code for this part).

I thought it would be pretty easy with a loop, but I was not able to check if the number already created exists. The cycle will contain only the first 5 numbers, because the last number can be equal to one of the other 5 .

+4
source share
5 answers

Let me offer you a simpler solution.

  • 1 45.
  • , Math.random ( -, Array.sort, ) . .
  • 5 .
  • , , div.

, ( ) ( DOM).

.:)

+11

?

$(function() {
  $('button').on('click', function(e) {
    e.preventDefault();
    
    var numArray = [];
    
    while( numArray.length < 5 ) {
      var number = Math.floor((Math.random() * 45 ) + 1);
      if( $.inArray( number, numArray ) == -1 ) {
        numArray.push( number );
      }
    }
    numArray.push( Math.floor((Math.random() * 25 ) + 1) );
    $('div').html( numArray.join("<br />") );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Generate</button>
<div></div>
Hide result
+4

, , lodash, , :

_.sample(_.range(1, 46), 5) // the 5 numbers from 1..45
_.random(1, 26)             // one more from 1..25

- . , , Javascript Allonge, .

+3

http://jsfiddle.net/015d05uu/

var tzoker = $("#tzoker");
var results = $("#results");
tzoker.click(function() {
    results.empty();
    var properResults = [];
    var rand = 0;
    var contains = false;
    for (i = 1; i < 7; i++) {
        do 
        {
         (rand = Math.floor((Math.random() * (i != 6 ? 45 : 25)) + 1));
          contains = properResults.indexOf(rand) > -1;
        } while(contains)
        results.append("<br />", rand, "<br />");
        properResults.push(rand);
    }
});

. . , .

+1

, 1 maxValue , . , , #randomNumbers.

HTML

<div id="randomNumbers"></div>

JS ( jQuery)

var randomNumbersArray = [];

$(function() {
    generateRandomNumbers();
    displayRandomNumbers();
});

function generateRandomNumbers() {
    for (i = 0; i < 5; i++) {
        generateRandomNumberFrom1To(45);
    }
    generateRandomNumberFrom1To(25);
}

function generateRandomNumberFrom1To(maxValue) {
    var randomNumber;
    do {
        randomNumber = Math.ceil(Math.random() * maxValue);
    } while ($.inArray(randomNumber, randomNumbersArray) > -1);
    randomNumbersArray.push(randomNumber);
}

function displayRandomNumbers() {
    for (i in randomNumbersArray) {
        $("#randomNumbers").append(randomNumbersArray[i] + "<br>");
    }
}
+1
source

All Articles