Random number within TWO ranges

Is there anyway to select a random number within TWO ranges ? For example, a random number between the range (10 to 50) OR (100 to 200).
Thank you !

This is a simple class that produces a number between a range:
class RandomRange
static java.util.Random random= new java.util.Random();
*    Return an int between n1 and n2
static int getIntBetween(int n1, int n2) // n2 must be greater than n1 or n2-n1 must be positive
// get random number between 0 and the range(n2 - n1)
int result= random.nextInt(n2- n1);
// plus the offset
result += n1;
return result;
// return random.nextInt(n2 - n1) + n1;
// the result is n2 exclusive, to make it inclusive return (result + 1)
*    Return a double between d1 and d2
static double getDoubleBetween(double d1, double d2)
return random.nextDouble()*(d2 - d1) + d1;
// d1 and d2 can be any value
*    Return a float between f1 and f2
static float getFloatBetween(float f1, float f2)
// similar
}----------------------------------

Similar Messages

  • How to get a random number in a range?

    as title
    how to get a random number in a range?
    like 2000~3000 thks :)

    int between 10 and 20 with the method Math.random():
    public class Rnd
         // Test
         public static void main(String[] args)
             int start=10, end = 30;
             for (int i = 0; i < 10; i++)
                int n = (int)(start + Math.random() * (end-start));
                System.out.println(n);
    }best regards.

  • How to generate a random number within a specified tolerance and control that tolerance.

    I am trying to simulate data without using a DAQ device by using a random number generator and I want to be able to control the "range" of the random number generated though.  On the front pannel, the user would be able to input a nominal number, and the random number generator would generate numbers within plus or minus .003 of that nominal number.  The data would then be plotted on a graph.  Anyone know how to do this?  Or if it's even possible?
    Just for information sake, the random number is supposed to look like thickness measurements, that's why I want to simulate plus and minus .003 because the data could be thinner or thicker than the nominal.  
    Thanks in advance!!
    Solved!
    Go to Solution.

    You can create a random number with a gaussian probability profile using two equal distributed (0...1) random numbers and applying the Box Muller transform.
    I wrote one many years ago, her it is. (LabVIEW 8.0). 
    Message Edited by altenbach on 04-12-2010 09:13 PM
    LabVIEW Champion . Do more with less code and in less time .
    Attachments:
    BoxMuller.vi ‏10 KB

  • Random number between a range

    hi all!
    how can i find random number between an specified range
    for example b/w 5-10
    thanks to all
    smh

    Here's a practical instance;-import java.util.Random; // Maybe you forgot this
    public class ImplementRandom {
      public void getRandom(int from, int range) {
         int newRandom;
         Random random = new Random(); 
         newRandom = from + random.nextInt(range);
         System.out.print(newRandom); 
      public static void main(String[] args) {
         ImplementRandom IC = new ImplementRandom();
         IC.getRandom(1, 100);
    }Actually that uses public void rather than public int as you cannot reference a non-static (return-type) method from a static context.

  • Generating random number within size of map problem (why me!!) ?

    Hi Guys,
    I'm trying to generator random numbers between 0 and a map width and another random number between 0 and a map height i.e if the map width was 3 i can generator 0,1,2.
    The coding i am using to do this is :
    int randomCol;
    int randomRow;
    randomCol = newMapWidth - 0 + 1;
    int itemp = generator.nextInt() % randomCol;
    if (itemp < 0)
          itemp = -itemp;
    randomCol = 0 + itemp;
    randomRow = newMapHeight - 0 + 1;
    int jtemp = generator.nextInt() % randomRow;
    if (jtemp < 0)
         jtemp = -jtemp;
    randomRow = 0 + jtemp;I've had a look at similar problems and searched penalty but can't seem to get it right for whatever way i implement. It leads to some array out of bound errors.
    If any can help me resolve this problem it would be greatly appreciated.
    Thanks A lot !

    Hippolyte wrote:
    randomRow = 0 + jtemp;I'll bite: what's the "0 + " voodoo for?It?s for clarity and Code readability, I guess. @OP: Random.nextFloat() generates numbers from 0.0f to 1.0f. Multiplying this number with your max value will generate a number between 0 and that given max value. BTW, you can generate numbers from -a to a by using (Random.nextFloat()- .5f) * (2 * a).
    Shazaam.

  • Random number between a range fix

    Hello
    I need to place an object on the stage.x randomly but not going .
    The stage is 1024 pixel and the object 726. I do the following, it works ok but sometimes some part of the object goes of the stage. Could you tell me what I do wrong?
    menucenter=Stage.width-_root.object._width;
    _root.object._x=Math.floor(Math.random() * (menucenter - 0)) - 0;
    Thank you
    George

    if the object has reg point at it's left edge use:
    _root.object._x=Math.random()*menucenter;

  • Get a random number between 2 numbers?

    Are their any classes which can produce a random number within a set of numbers i specify?
    If their are no predefined java classes then it doesnt matter.
    Thanks

    No as far as I know, but its easy to create one:
    double low_Limit, super_Limit;
    double interval = super_Limit - low_Limit;
    //Generate a random number between 0 and 1, with a Java satandard class
    double random_number = Math.random();
    //Now we generate a random numbre between 0 and intervalo:
    random_number = random_number * intervalo;
    // now we generate a random number between low_Limit super_Limit:
    random_number = random_number + low_Limit;
    //done :)
    Abraham.

  • "Battery serial does not validate", but the number is within the range

    My sister came home from abroad for Christmas, and I checked her PB 12-inch battery serial number. Her battery has the serial number ZZ3480FJPVEA as far as I can see. This falls into the replacement range:
    12-inch
    iBook G4 A1061 ZZ338 - ZZ427.
    On the exchange page, Apple writes: "If the first 5 digits of your battery’s 12-digit serial number fall within the noted ranges, please order a replacement battery immediately." But the battery serial does not validate even if I replace the zero with the letter "O".
    Are there batteries within the range that still are ok?
    Ingmar
    PowerBook G4 12-inch   Mac OS X (10.4.8)  

    I could not post an answer to the topic without marking the question
    "answered", though it wasn't!
    Strange, because the question is not marked as answered and it is not necessary to mark it in order to reply (simply click on the "reply" link near each post you want to reply to).
    However when you feel that your question is answered - or the forum cannot be of further assistance - mark the question as answered and maybe also give some final notes.
    If you got helpful replies, then you may award the posters by granting points. You can do so by clicking to "helpful" and "solved" buttons appearing near each post (you need to be logged in).
    The buttons mean what they state: "Helpful" in the sense of user gave a useful answer or further information allowing you to solve an issue with some work of your own. "Solved" means that this post of the user is mainly responsible for managing an issue.
    You can only mark one posting as "solved" in a thread, and - I hope this is correct - two or three times marking posts as "helpful". With the last, I'm not sure, you may have a look at "Help & Terms of Use".

  • Random Number Generation Within An Object

    Hi, im trying to create an Arraylist containing 10 objects from class Child (see below). Each Child has an age between 1 and 30 which should be randomly generated but for some reason each one is the same. However when i use the BlueJ debugger and step through the program it creates appropriately random numbers so im assuming the problem is with the speed at which the code is run. Any ideas as to how i can combat this? Heres the code:
    Main Class:
    public static void main(String args[]) {
    int index = 0;
    while(index < 10) {
              test = new Child();
              int age = test.getAge();
              schoolbus.add(test);
              System.out.println((index + 1) + ": " + age);
              index++;
    Child Class:
    public class Child {
    private int age;
    Random r = new Random();
    public Child() {
    age = r.nextInt(30);
    public int getAge() {
    return age;
    Thanks, Nick

    You're creating 10 new Random() objects within the same millisecond, this gives them all the same seed and they produce the same first number. You could produce all ages from the same Random() outside the child class and set the age within the child's constructor e.g.
    //snip
    //This bit refers to the Main class
    Random r = new Random();
    while(index < 10) {
    test = new Child(r.nextInt(30));
    //snip- Mr K

  • Same pseudo random binary number on two different laptops

    I want to generate same pseudo random binary number on two different laptops at the same time.
    How can I do that. Please provide suggestions.  
    JK

    Hi Joseph,
    I don't have any examples of this. Usually you use PRNGs to generate unique numbers…
    You need to create your own algorithm.
    There are USB sticks available that generate unique numbers in a certain reproducable way, which are used for authentification of bank account operations. You might take them as inspiration for your task…
    Best regards,
    GerdW
    CLAD, using 2009SP1 + LV2011SP1 + LV2014SP1 on WinXP+Win7+cRIO
    Kudos are welcome

  • Autocreate item number within a number range

    A newbie question:
    Can SBO auto generate an item number when the user adds a new item via the Item Master Data screen? Is it possible to define this number within a number range?

    As Harold says, with formatted search you can do many nice things...
    Also take a look at the <a href="http://msdn.microsoft.com/library/default.asp?url=/library/en-us/tsqlref/ts_aa-az_3ied.asp">Trans-SQL reference</a> (if you are using SQL server as a database server), here you can find loads of information about the Trans-SQL language of SQL server...

  • Random Number generation within BPEL

    I am trying to embed a java-exec and trying to generate random number using a code as follows:
    int ranNumber1 = (int)(Math.random()*1000000000000000.0);
    int ranNumber2 = (int)(Math.random()*1000000000000000.0);
    setVariableData("RanNumber1",new Integer(ranNumber1));
    setVariableData("RanNumber2",new Integer(ranNumber2));
    I always get the same value for ranNumber1 and for ranNumber2 and for every instance, the value seems to be the same.. Actually the value generated is 2147483647 always..
    Am I doing anything wrong? Can anyone clarify here, please...

    // construct a bigdecimal, exaclty lenght'd 10 digits
    BigDecimal z = new BigDecimal("10000000000");
    // multiply it randomly (random returns something between 0 and 1)
    z = z.multiply(new BigDecimal(Math.random()));
    // and use the rounding ..
    BigInteger big = z.toBigInteger();
    is one option, I guess not the nicest but working ..

  • Random number in range generator plz help!

    hey hope someone can help me out, im sure its an easy one:
    var tstArray:Array = new Array(1,2,3);
    for (var a:uint=0; a<tstArray.length; a++)
    var x:Number = Math.floor((Math.random()*tstArray[a]));
    trace(x);
    tstArray.splice(a,1);
    i have this code but it doesnt do exectply what i want it to do. Im trying to generate a signle random number per click between 1 and 3 and when all numbers have been used up, remove this click listener.
    if u can help it'll be much appriciated
    thx pavel

    use:
    var fp1:farm_part1=new farm_part1();
    and any time you want to randomize an array use:
    var tstArray:Array = fp1.randomizeF([1,2,3]);
    package
    */import flash.utils.Timer;
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.*;
    import flash.media.Sound;
    import flash.events.TimerEvent;
    import flash.media.SoundChannel;
    import flash.media.SoundTransform;*/
    public class farm_Part1
    public function randomizeF(a:Array):Array
    {a.shuffle();
    return a;
    ///////////////////////////// change nothing below /////////////////////////////////////////
    function shuffle(a:Array)
    var p:int;
    var t:*;
    var ivar:int;
    for (ivar = a.length-1; ivar>=0; ivar--)
    p=Math.floor((ivar+1)*Math.random());
    t = a[ivar];
    a[ivar] = a[p];
    a[p] = t;
    }//randomAnimal
    }//class
    }//package

  • Problem with random number generation

    hey forum, i wonder if anyone can help me out with a small problem with my university coursework (yep its homework!!!)
    heres my problem, i am writing one of them 8 puzzle problems (the one based around sam lloyds 15 puzzler), i can successfully generate one random sequence of numbers with no duplicates, but whenever i call the random method again it keeps producing the same results
    heres the code
    in my main class file
    if(e.getSource() == randomButton) {
          new RandomPuzzle();
          System.out.println(random.randState);
          //startStateString = new RandomPuzzle();
    }heres my number generator class file
    import java.util.Random;
    import java.io.*;
    public class RandomPuzzle
         /** Base Random number generator */
        Random rn = new Random();
        /** Puzzle holder */
        byte b[];
        long number = 0;
        String randState = "";
        /** Default constructor */
        public RandomPuzzle() {
            rn.setSeed(number);
            b = new byte[9];
            randState = randomString();
        /** Provide range for generation */
        public int rand(int lo, int hi) {
            int n = hi - lo + 1;
            int i = rn.nextInt() % n;
            if (i < 0)
            i = -i;
            return lo + i;
        /** Set size for array */
        public int rand( int hi){
            int n = hi;
                return n;
        /** Check for duplicate values within the same configuration */
        boolean valueExists( byte value ) {
            int i = b.length;
            boolean exists = false;
            for( int j = 0; j < i; j++ ){
                if( b[j] == value )
                    exists = true;
            return exists;
        /** returns the actual string */
        public String randomString(int lo, int hi) {
            int n = rand( 9 );
            //boolean valueEntered = false;
            for (int i = 0; i < 9; i++) {
                boolean valueEntered = false;
                byte temp = (byte)rand('0', '8');
                while( valueEntered == false ) {
                    if( !valueExists( temp ) ) {
                         b[i] = temp;
                         valueEntered = true;
                    else
                        temp = (byte)rand('0', '8');
            return new String(b, 0);
        /** calls above function */
        public String randomString() {
            return randomString(0, 8);
    }i've tried for hours to work this out, but i am stumped. if anyone can point me in the right direction, maybe point out the problem code and give one or two tips i would be forever in your debt
    thanx in advance
    korbitz

    thanx for the help paulcw, but when i removed the seed code it done the same
    but i added this to my main class and now it works fine
    if(e.getSource() == randomButton) {
                   RandomPuzzle temp = new RandomPuzzle();
                   System.out.println(temp.randState);
                   //startStateString = new RandomPuzzle();
              }thanx again for your help

  • Desperate HELP with Random Numbes in an Array & Do / While

    Please somebody help, I have been working this problem for over 7 days now and can't get it. I have tried everything from a while to a do while to this and that. I need to have an Array of 8 that when run will produce random numbers for output between 15 to 25. I CAN"T GET IT PLEASE HELP. I am new to JAVA and have done everything I can think of to resolve this. I even have purchased a new book and looked at every site trying to find a solution. PLEASE HELP! Here it is:
    import javax.swing.*;
    public class RandomArray{
    public static void main (String [ ] args) {
    JTextArea outputArea = new JTextArea ( );
    int myArray [ ]; //array declaration
    myArray = new int [ 8 ]; //allocating memory
    String output = "Array values at initializatioon ";
    output += "\nIndex\tValues";
    for ( int i = 0; i < myArray.length; i ++)
    output += "\n" + i + "\t" + myArray [ i ];
    output += "\n\nArray values after assigning values within the range of 15 and 25";
    do {( int i = 0; i <myArray.length; i++)
         while     myArray [ i ] = 15 + (int) (Math.random ( ) * 25);
    output += "\n" + i + "\t" + myArray [ i ];}
    outputArea.setText (output);
    JOptionPane.showMessageDialog (null, outputArea,
    "Array Value before and after",
    JOptionPane.INFORMATION_MESSAGE);
         System.exit ( 0 );
    The output that I need is in two columns one with the initial array 0-7 and the second should be random numbers 15-25. Please help, please

    here you are :
    import javax.swing.*;
    public class RandomArray
    public static void main (String [ ] args)
         JTextArea outputArea = new JTextArea();
         int       myArray [] = new int[8];
         String output = "Array values at initializatioon ";
         output += "\nIndex\tValues";
         for (int i = 0; i < myArray.length; i ++)
              output += "\n" + i + "\t" + myArray [ i ];
         output += "\n\nArray values after assigning values within the range of 15 and 25";
         for (int i = 0; i < myArray.length; i++)
              myArray [ i ] = 15 + (int) (Math.random ( ) * 10);
              output += "\n" + i + "\t" + myArray [ i ];
         outputArea.setText(output);
         JOptionPane.showMessageDialog (null, outputArea,
              "Array Value before and after",
              JOptionPane.INFORMATION_MESSAGE);
         System.exit(0);

Maybe you are looking for

  • How to unlock my iPhone 4?

    I purchased an iPhone 4 from Vodafone, staff told me I could unlock the phone for use on any carrier network via iTunes, but can't see how to do it. Am currently overseas and need this phone unlocked so that I can use various SIMs and networks wherev

  • Code to call a function when enter key is pressed

    hi all, In a table control program i need to call a function when i press enter key... but im not able to do that since the function is always called when i press a push button on the screen.... can any one help me in this.. please....

  • PreparedStatement Object Query

    Hi, If i use the same PreparedStatement object for two queries, will it cause any issues. Example: //start program PreparedStatement ppt = null; ppt = some query; ppt.executeUpdate(); if i try to use the same object for other query, will it cause any

  • Word and Excel Doucments...blank!

    A few weeks ago my computers automatic update thingy came up on the screen...I don't remember what it was for...I clicked for it to update. Since then I can open word and excel documents but they are blank pieces of paper, like nothing was typed by t

  • How to monitor messages at BAPI side of integration scenario

    Hi all, In scenarios like Soap -> Abap proxy (XI Adapter), I can monitor both sender and receiver messages on sxmb_moni (on XI side and on ECC side). When the scenario is Soap -> BAPI (RFC Adapter), how can I see the messages in the ECC side? thanks!