Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random lottery number generator

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

I thought it would be pretty easy using a loop, but I've found myself unable to check if the number generated already exists. The loop would only contain the first 5 numbers, because the last number can be equal to one of the other 5.

like image 984
kogigr Avatar asked Nov 29 '22 10:11

kogigr


2 Answers

Like this?

$(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>
like image 28
LinkinTED Avatar answered Dec 09 '22 19:12

LinkinTED


Let me propose you some simpler solution.

  1. Make a list of all numbers from 1 to 45.
  2. Sort the list using Math.random (plus minus something, read the docs of Array.sort to find out) as the comparison function. You will get the list in random order.
  3. Take 5 first items from the list.
  4. Then, when you already have the numbers, put them all into your div.

This way you don't mix your logic (getting the numbers) with your presentation (putting stuff into the DOM).

I leave the implementation as an exercise for the reader. :)

like image 68
mik01aj Avatar answered Dec 09 '22 19:12

mik01aj