[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 778
  • Last Modified:

Question on Random.

how can I generate random numbers say range between 1-255?
and what's the function used in JAVA to randomise the seed so that the same number won't be generated so often.

Thanks for any help offered!
0
justinng
Asked:
justinng
1 Solution
 
vendrigCommented:
Here's the code to do it (I hope the tabs will survive;). I made an application so that you can test it easily. E.g., you should call it with <COMMAND>java MyRandom 1 255</COMMAND>. The function showRandomNumbers retrieves a random number between 0 and 1 and then maps it to the given range. It prints a list of 100 such numbers as an example. The same function can be used in an applet, and you can do with it what you want (like putting the numbers in an array).

import java.util.Random;
import java.lang.Math;

class MyRandom
{
      public static void main (String args[])
      {
            if (args.length!=2)
                  System.out.println("Usage: java MyRandom [minimum: Integer] [maximum: Integer]");
            else
                  showRandomNumbers(Integer.parseInt(args[0]),Integer.parseInt(args[1]));
      }

      private static void showRandomNumbers(int lo, int hi)
      {
            // note: limits lo and hi are included in range
            Random r = new Random();      // default: seed based on current time
      // or:      Random r = new Random(123);      // fixed seed
            for (int i=0; i<100; i++)
            {
                  int randomNr=lo+(int) Math.round((hi-lo)*r.nextDouble());
                  System.out.print(randomNr+" ");
            }
      }
} // end class MyRandom

If you have JGL at your disposal, consider using COM.objectspace.jgl.Randomizer. This would reduce the amount of code, because you can simply use getInt(lo,hi) on a Randomizer object.
0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now