www.webdeveloper.com
Results 1 to 10 of 10

Thread: NEWBIE: How to do array of random integers

  1. #1
    Join Date
    Dec 2005
    Posts
    21

    NEWBIE: How to do array of random integers

    OK so another question about arrays...

    I want to generate an array of random integers from 100 to 200...

    I think this is the way to get just one number. (Please correct if I am wrong!)

    import java.util.Random;
    generator = new Random();
    numbers = 100 + generator.nextInt( 100 );

    So i am trying to incorprate this into making an array of 400 random numbers fromm 100 to 200

    import java.util.ArrayList;
    numbers = new ArrayList();
    for( int i = 0; i < 400; i++ )
    {
    import java.util.Random;
    generator = new Random();
    numbers.add( 100 + generator.nextInt( 100 ));
    }

    so is this right?

    What if I wanted to make a list of 100 numbers from 100 to 200 and not reuse any numbers? How could I do that?
    Last edited by warriorjoe7; 12-17-2005 at 07:51 PM.

  2. #2
    Join Date
    Nov 2005
    Location
    The best country in the world, Texas!
    Posts
    251
    for starters, you're generally gonna want to put all your import lines together at the very top of the program.

    See the reply to your other post on making arrays and not ArrayLists. The code you want looks something like:

    Code:
    //400 random numbers [100,200]
    import java.util.Random;
    
    Random generator = new Random();
    int[] numbers = new int[400];
    for(int i=0; i<400; i++)
    {
        numbers[i] = (100 + generator.nextInt(101));
    }
    note that the nextInt function needs a parameter of 101 because it is exclusive at the high end (nextInt(x) returns a number from 0 to x-1)

    if you want to not reuse any numbers, you might do something like this, though this solution is certainly not very elegant, and I'm not exactly certain on the syntax of label breaks in java...even still, there's the problem that by the time you get to the last few iterations of the main loop, you only have a small chance of randomly digging up a number that hasn't been used yet...this program could potentially take a very long time to execute
    Code:
    //100 random numbers [100,200], none reused
    import java.util.Random;
    
    Random generator = new Random();
    int[] numbers = new int[100];
    int rand;
    for(int i=0; i<100; i++)
    {
        newRand:
        rand = (100 + generator.nextInt(101));
        for(int j=0; j<=i; j++)
        {
            if(rand == numbers[j]) break newRand;
        }
        numbers[i] = rand;
    }
    Last edited by Cytael; 12-18-2005 at 08:10 PM.

  3. #3
    Join Date
    Dec 2005
    Posts
    21
    Thanks alot Cytael. The first code looks perfect. The 2nd code is definitely usable. If anyone has any other ideas for the non-reused numbers (the 2nd code) please post.

    OK how did you do that code box thingy? there has to be a post somewhere for that.

  4. #4
    Join Date
    Sep 2005
    Location
    Chicago, Il
    Posts
    144
    In the box you type a reply, look at the top for the # sign. You just hignhlight the text you want to look like code, and hit that button. Or put code tags around the text in question.

  5. #5
    Join Date
    Dec 2005
    Posts
    21

    Thanks

    Thanks again big dog!

  6. #6
    Join Date
    Dec 2005
    Posts
    21
    OK I am having a problem declaring an array of strings and I found a workaround but it is slow and I am sure there is a much simpler way.

    Code:
    // 20 possible names
    String[] firstname = { "Aaron", "Bob", "Carrie", "Derek", "Erica", "Fred", "Harvey", "Isaac", "Joe", "Kevin", "Lee", "Marcy", "Oliver", "Paula", "Randy", "Shawna", "Troy", "Vince", "William", "Yvette" };
    
    // -------------- The code in question ------------------
    // list of 100 blank names
    String[] randomname = { "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "" };
    // -------------------------------------------------------
    
    Random generator = new Random();
    
    FileWriter out = null;
    try
    {
    for( int i = 0; i < 100; i++ )
    {
    	randomname[i] = ( firstname[generator.nextInt(20)] );
    
    	out = new FileWriter( "Names.xls", true );
      	out.write( randomname[i] + "\n" );
    	out.close();
    }
    }
    See the long array full of 100 ""s? I have tried to set up the array a ton of ways but this is the only thing I could find that works and it is a hassle because I have about 20 arrays to do this with, of all different sizes. I have tried:

    Int[] randomname = new Int[100];
    // of course this doesn't work they are strings not integers

    String[] randomname = new string[100];
    // nope

    String[] randomname = new Int[100];
    // nope

    ok so what is it?

  7. #7
    Join Date
    Dec 2005
    Posts
    21
    HOLY COW! I just found it... this pisses me off. I spent 3 hours because of a lowercase letter. This is insanity!

    String[] randomname = new string[100];
    // this will not work

    String[] randomname = new String[100];
    // With a capital letter in the second word "String" it works.

    OK so how do real programmer's keep from shooting themselves? i am going to need to know fairly quickly on this one.

  8. #8
    Join Date
    Apr 2005
    Location
    Perth, Australia
    Posts
    340
    To stop from shooting ourselves we write re-usable modular components.

    If you have a requirement to write something complicated or hard you can sit down puzzle it out and write it up, sure your done but if you come back to look at it later its hard to wade through it to see what it does or to update it.

    What you do is try to identify common elements and make worker functions and classes if its that big.

    Here is a few relative examples that you might find thought provoking:


    First of all the random numbers, I find it much easier to just call a funciton pass it your minimum and your maximum and have it return the value, no mess no fuss.

    Code:
    	private int rand(int min, int max)
    	{
    		double rand = Math.random();
    		rand = (rand *= max)+min;	
    		return (int)rand;
    	}
    Perhaps your only going to use the same minimum and maximum, some would say its a waste of time but what you can now is overload the method to make it automatic. Yet you still have the underlying worker to call incase you need a different set:

    Code:
    	private int rand()
    	{
    		return rand(100,200);
    	}
    	private int rand(int min, int max)
    	{
    		double rand = Math.random();
    		rand = (rand *= max)+min;	
    		return (int)rand;
    	}
    Ok next, your "used" number array, this is where i would employ boolean logic to make this task even easier:


    First i would define 2 methods:

    Code:
    	private void addNumber(int intValue)
    	{
    		int k=0;
    		boolean flag=true;
    		
    		while (flag)
    		{
    			if (numbers[k]==0)
    			{
    				numbers[k]=intValue);
    				flag=false;
    			}
    		k++;
    		}
    	}
    	
    	private boolean isNumber(int intValue)
    	{
    		for (int k=0;k<numbers.length();k++)
    		{
    			if (numbers[k]==intValue))
    				return true;
    		}
    		return false;
    	}
    You initialize your number array with values of zero so that you can just go through until it hits an open space and can add it in, then you easily just set the array to zero to reset it.

    So, finally with all the "work" put into modularised components running the system is as easy as a few method calls and some fancy logic:


    Code:
    	
    ...
    	int tempRand; 
    	
    	// prepare out put
    	out = new FileWriter( "Names.xls", true );
    
    	for (int k=0;k<=99;k++)
    	{	
    		do
    		{
    			//get a random number
    			tempRand = rand();
    		
    		}// do not continue untill unique random found
    		while (isNumber(tempRand));
    		
    		//get corresponding name
    		randomname[k] = firstname[temprand];
    
    		//write to output file
      		out.write( randomname[i] + "\n" );
    
    		//random name now taken, add to array
    		addNumber(tempRand);
    	}
    
    	//close output
    	out.close();
    ...
    Maintainable, easy to understand and modularised narrowly averting the need for high velocity projectiles.

    I doubt this would all compile, plus it would be good practice to write anyway.

    Waylander.
    Last edited by Waylander; 12-23-2005 at 01:19 AM.

  9. #9
    Join Date
    Dec 2005
    Posts
    21
    Thanks alot for getting me going. I will need the non reused code in the next few weeks sometime so I will try to write it. This will help. And thanks for the good general advice too.

    Joe

  10. #10
    Join Date
    Apr 2005
    Location
    Perth, Australia
    Posts
    340
    No Worries,

    Yeah it is nice to stay ahead a little bit, lol it keeps people guessing..

    Waylander.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles