CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Feb 2011
    Posts
    8

    Lottery simulation

    heya, Heya I wanted to simulate a lottery in java. I'm no experienced user so have patience with me.
    This is what I have done so far;
    public class uppfit3 {
    public static void main(String[] args)
    {
    new lottery ( 500 );
    }
    }

    class lottery {
    private int[] numbers;

    public lottery ( int n )
    {


    numbers = new int[n];

    // Initialize lottery numbers
    int i = 0;

    while ( i < n ) {
    int r = (int)( Math.random() * n );

    if ( add ( numbers, i, r ) ) {
    ++i;
    }
    }

    show_all ( numbers );
    }

    private boolean add ( int[] list, int size, int val )
    {
    for ( int i = 0; i < size; i++ ) {
    if ( list[i] == val ) {
    return false;
    }
    }

    list[size] = val;

    return true;
    }

    private void show_all ( int[] list )
    {
    for ( int i = 0; i < list.length; i++ ) {
    System.out.print ( list[i] + " " );
    }
    System.out.println();
    }
    }

    The foregoing code randomize 500 numbers, which is the number of tickets that will conclude in the lottery. And it (the code) also prevents 2 numbers to occur twice

    I'm looking to have 3 different profit limits; 1000 £ and 100.000 £. I'm not sure whether
    a constant winning percentage or one for each profit.
    The number of drawn lottery tickets are specified by the user, the outprint should look like this; enter number of entries (**) <-- a number choosed by the user
    and then (example);
    Lottery numbers
    324 - win: 1000 kr
    201
    The first one of them was randomly a winning ticket.

    I'm kind of stuck here, and I would appreciate if someone could put me on the right track, even the slightest help is welcomed.
    best regards
    Bertil

  2. #2
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Lottery simulation

    When posting code, use the CODE tags (see my sig) and the Java naming conventions (class names begin with an uppercase letter, variable and method names begin with a lowercase letter) if you want people to read your code.

    If you want to get a random integer within set limits, it's a lot simpler to use the Random class method Random.nextInt(..).

    But if you just want a random array of numbers from 1 to 500 with no duplicates, just fill an Integer array with 1 to 500 and shuffle it with the Collections.shuffle(..) method (using the Arrays list wrapper):
    Code:
    // create array
    Integer[] numbers = new Integer[500];   
    
    // fill it with 1 to 500
    for (int i=0; i<numbers.length; i++) {
        numbers[i] = i+1;
    }
    
    // shuffle it
    Collections.shuffle(Arrays.asList(numbers));
    
    // print it out
    for (int num : numbers) {
        System.out.println(num);
    }
    Remember to use an Integer array, not an int array.

    So, anyway, exactly what are you stuck on?

    Good programmers know what's beautiful and bad ones don't...
    D. Gelernter
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  3. #3
    Join Date
    Feb 2011
    Posts
    8

    Re: Lottery simulation

    Oh I see, yea, that look a lot more elegant!

    Correct me if i'm wrong but the next thing to create a method that makes a win-list for the two types of winning tickets (in my case 1000 £ and 100.000 £).
    ..And then implement a method that tests which of the drawn numbers actually are winning tickets?

  4. #4
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Lottery simulation

    I seems to me that there's more than one way to skin a cat...

    You could, for example, replace the Integers in the array with a List holding class objects that contain two Integers - a lottery number and a prize amount. You can still shuffle by the lottery number if the class implements the Comparable interface (or you could use a separate Comparator). This way, the prize and the lottery number are tied together, and once a number is picked, you get the prize value with it. This is fine for small lotteries, but for very big lotteries it wastes memory for all the numbers that have a zero prize amount.

    Alternatively, you can use the original array of Integers, and keep a separate list of objects that each contain a lottery number that has a prize and what the prize is. When a number is picked, you look it up in the prize list, and if it's found, the prize value is right there. This is OK for large lotteries with relatively small number of prizes.

    The most efficient option is to forget the array of random numbers altogether, and only keep a list of the numbers that have prizes. If a number is chosen that isn't in the list, there's no prize. This way, you can either use a class that contains a winning number and its prize - which allows you to have many different prize values, or you can have a separate list of lottery numbers for each prize value. This is simpler, but means you're stuck with the prize values you specify at the start.

    If it was me, I'd write a class that holds a lottery number and a prize value, generate the required number of those objects as prize winners, giving each a random lottery number and a prize, and put them into a list or array (you'd have to check for duplicates this way) . Whatever number the customer chose, I'd look it up in the list or array, and if it was found it would be a winner and the prize value would be with it, and if it wasn't found it would be a loser. This way you don't have to store all the losing numbers, and you can have as many prizes with different values as you want

    YMMV.

    There may be other solutions I haven't thought of. This is why it's important to gain a thorough understanding of the problem and how you can best solve it for your particular situation before writing any code. Writing code should just be translating your solution into Java.

    That simplicity is the ultimate sophistication. What we meant by that was when you start looking at a problem and it seems really simple with all these simple solutions, you don't really understand the complexity of the problem. And your solutions are way too oversimplified, and they don't work. Then you get into the problem, and you see it's really complicated. And you come up with all these convoluted solutions. That's sort of the middle, and that's where most people stop, and the solutions tend to work for a while. But the really great person will keep on going and find, sort of, the key, underlying principle of the problem. And come up with a beautiful elegant solution that works...
    Steve Jobs
    Last edited by dlorde; February 24th, 2011 at 04:30 PM.
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  5. #5
    Join Date
    Feb 2011
    Posts
    8

    Re: Lottery simulation

    okay, thanks for the help. I'll give it a shot

  6. #6
    Join Date
    Oct 2008
    Posts
    50

    Re: Lottery simulation

    Let me see if I get this correctly. There are 500 tickets, two of which are winning tickets with different prizes. You want the user to be able to specify a number of tickets he wants to "buy" and tell him if he won anything?

    Why is there even a need to randomize the tickets? It seems to me like the actual number on the ticket is completely irrelevant. You could easily give them the tickets sequencially. As long as the winning ticket is random, the sequence in which you give out the tickets is irrelevant. (i.e., randomizing something that's already random is redondant.)

    So the very easiest way to do this would be something like:
    Code:
    class Lotery{
       int limit;
       int current;
       int firstPrize;
       int secondPrize;
      
       public Lotery(int max){
          limit = max;
          current = 1;
          firstPrize = (int)Math.random()*limit;
          do
          {
              secondPrize =  (int)Math.random()*limit;
          }while(firstPrize != secondPrize); 
       }
    
       public int pick()
       {
             if(current > limit)
                 return -1;
             return current++;
       }
    
       public int getPrize(int ticket)
       {
            if(ticket == firstPrize)
                return 100000;
            if(ticket == secondPrize)
                return 1000;
            return 0;
       }
    }
    Am I missing something?
    Last edited by Filobel; February 24th, 2011 at 05:11 PM.

  7. #7
    Join Date
    Feb 2011
    Posts
    8

    Re: Lottery simulation

    An intresting solution . The only thing that's missing is the winning percentage for the 2 prices. And then at last an input to let the user choose the number of tickets that he wants to be drawn. Thank you for your help, Filobel.

  8. #8
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Lottery simulation

    Quote Originally Posted by Filobel View Post
    Am I missing something?
    Looks good to me - inflexible but simple & efficient, and seems to fit the requirements

    Successful software always gets changed...
    F. Brooks
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  9. #9
    Join Date
    Feb 2011
    Posts
    8

    Re: Lottery simulation

    Filobel, how do I get your code to work? it doesnt have a main method, and its error if i add one anyway..

  10. #10
    Join Date
    Oct 2008
    Posts
    50

    Re: Lottery simulation

    Sorry it took me so long to reply.
    I wrote that code out of thin air directly on here, so it is quite likely that there are some mistakes. I just wrote the general idea, assuming you would be able to go on from there.

    I also assumed you only had 2 prizes and that the winning percentage of each was 1/max_tickets. If you want a set winning percentage, then that would need to be additional parameters to the constructor and the prizes would need to be int[] rather than just int (because you'd have more than one winning ticket for each prizes). To calculate the number of tickets, you'd do:

    int = (int)Math.ceil(winPercentageFirstPrize*max); //can be Math.floor, though that would mean you may have no winning tickets.

    Input outputs from the console are pretty easy. System.out.println for output, for input you do:
    BufferedReader reader = new BufferedReader(System.in);
    String input = reader.readLine();

    You can then do:
    int nbTickets = Integer.parseInt(input);
    To turn the input into an integer that corresponds to the number of tickets and call the pick and getPrize methods that many times (using a for loop). Output the amount won for each ticket (along with a little message if you want).
    Last edited by Filobel; March 2nd, 2011 at 10:04 AM.

  11. #11
    Join Date
    Feb 2011
    Posts
    8

    Re: Lottery simulation

    Hey, I've tried to get this lottery program to work, but it seems like there are no winning tickets. My guess is that the for-loops (in the 2 prize list methods) overwrites the data and thus no winning tickets are included. Do anyone know what I should do?
    Code:
    import java.util.Random;
    import java.util.Scanner;
    
    public class LOTTERYDENRATTA {
    	static int ticket; 
    
    
    	static int firstPrize, secondPrize, limit = 500, randomNumber1,
    			randomNumber2, randomNumber3;
    
    	public static void main(String[] args) {
    		System.out.println("Tickets cost $10.");
    		System.out.println("Lottery numbers with the med. win $1000:");
    		System.out.println();
    		PrizeList1();
    		PrizeList2();
    		pick();
    		awards();
    
    	}
    
    	// This method ticket number for the second prize
    	private static int PrizeList1() {
    		firstPrize = (int) Math.random() * limit;
    
    		Random number = new Random();
    		System.out.println();
    
    		for (int counter = 1; counter <= 10; counter++) {
    
    			randomNumber1 = number.nextInt(500);
    			System.out.println(randomNumber1);
    
    		}
    
    		System.out.println();
    		return randomNumber1;
    	}
    
    	// This method shows the ticket numbers for the first prize
    
    	private static int PrizeList2() {
    		Random number = new Random();
    		secondPrize = (int) Math.random() * limit;
    
    		System.out.println("Lottery numbers with the win $1,000,000: ");
    		System.out.println();
    
    		for (int i = 1; i <= 1; i++) {
    			randomNumber2 = number.nextInt(500);
    			System.out.println(randomNumber2 + " ");
    
    		}
    		System.out.println();
    		return randomNumber2;
    	}
    
    	// This method lets the user choose how many of the 500 tickets he wants to
    	// be drawn
    	private static void pick() {
    		Scanner Keyboard = new Scanner(System.in);
    
    		Random number = new Random();
    		System.out.print("How many tickets do you want? ");
    		ticket = Keyboard.nextInt();
    
    		for (int i = 1; i <= ticket; i++) {
    			randomNumber3 = number.nextInt(500);
    
    			System.out.println(randomNumber3 + " ");
    
    		}
    	}
    
    	// This method calls the previous methods, controlling if the numbers you
    	// picked is a winning ticket
    
    	private static void awards() {
    		int nbTickets = randomNumber3, nbTickets1 = randomNumber3;
    
    		if (nbTickets == firstPrize)
    			System.out.print("You have won $1,000,000!");
    
    		if (nbTickets1 == secondPrize)
    			System.out.print("You have won $1000!");
    
    		else {
    			Scanner kb = new Scanner(System.in);
    			System.out.println("\nPress ENTER to continue.");
    			kb.nextLine();
    			System.out.print("Sorry, you lose.");
    		}
    	}
    }
    I would appreciate if anyone could take time and help me.
    Last edited by Bertil; March 7th, 2011 at 01:42 PM.

  12. #12
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Lottery simulation

    For a start indent your code so it makes it easier to see what code belongs to what code block and then add some comments to explain what each section of code is doing.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

  13. #13
    dlorde is offline Elite Member Power Poster
    Join Date
    Aug 1999
    Location
    UK
    Posts
    10,163

    Re: Lottery simulation

    Quote Originally Posted by Bertil View Post
    I would appreciate if anyone could take time and help me.
    It doesn't follow the Java naming conventions, as previously advised; and why use Random and Math.random() ?

    I'm not inclined to make an effort and give advice if you're not prepared to follow it.

    Programs must be written for people to read, and only incidentally for machines to execute...
    H. Abelson and G. Sussman
    Please use &#91;CODE]...your code here...&#91;/CODE] tags when posting code. If you get an error, please post the full error message and stack trace, if present.

  14. #14
    Join Date
    May 2006
    Location
    UK
    Posts
    4,473

    Re: Lottery simulation

    As well as not conforming to Java naming standards you have used confusing names. Why for instance is the second prize generated by method PrizeList1 and the result stored in 'firstPrize' and the first prize is generated by PrizeList2 and stored in 'secondPrize' or are your recently added comments all wrong.

    And why after generating the prize numbers do you then loop and generate more numbers which you return but never use.

    And why do you ask how many tickets the user wants and then only keep a record of the last number you generated.

    I think you need to have a careful look at your code and ask yourself what each line is actually doing and is it correct.

    BTW please don't go back and edit earlier posts after responses have been made to it, it just makes it even more difficult for other people to follow the thread.
    Posting code? Use code tags like this: [code]...Your code here...[/code]
    Click here for examples of Java Code

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured