Creating random numbers

how do you create random numbers between a given set of integers?
for example, how would you create random numbers from 2 to 9?

public class Test {
    public static void main (String[] parameters) {
        for (int i = 0; i < 100; i ++) {
            if (i > 0) {
                System.out.print (", ");
                if (i % 10 == 0) {
                    System.out.println ();
            System.out.print ((int) (8 * Math.random ()) + 2);
}code]Kind regards,
  Levi                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

Similar Messages

  • Program to create random numbers in plsql

    How do we Write a program to create random numbers.
    Thanks

    No need to - we have DBMS_RANDOM :)

  • Create Random Numbers using OLE Randomize and RND

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

    Hi,
    I've managed to create an excel spreadsheet by creating an object of type EXCEL.APPLICATION. I've also managed to rename the worksheet tabs, move from one tab to another as well as fill certain cells with numbers.
    I would now like to create a range of random numbers within one of these worksheets. I believe I should be using the Randomize and RND methods contained within the VBA OLE object. This is what I've done so far :
    DATA: gs_vba TYPE ole2_object,           "VBA object
               gs_math TYPE ole2_object.
    CREATE OBJECT gs_vba 'VBA'.
    CALL METHOD OF gs_vba 'MATH' = gs_math.
    CALL METHOD OF gs_math 'Randomize' = gs_math.
    CALL METHOD OF gs_math 'Rnd' = gs_math
      EXPORTING
        #1 = 1000.
    Is the above the right way to do it? If not, I would really appreciate your help, and if possible, some sample code to do this as well.
    Thanks and regards,
    Adeline.

  • How do I generate an array of random numbers that relate to an output wave that falls within a certain frequency range?

    I have been creating random numbers that I'm using within a system, the system is working fine, but now I have realised that the random numbers must be outputted to speakers in such a way as to filter out all but a low frequency range.
    I was thinking about generating a dither signal with a bandpass filter, but could not get it to give me out a full array of 250 values which I could then manipulate.
    The sampling frequency of the output is 200Hz and the 250 data points must fall within the 0-100Hz range.
    Another course of action I am considering is to use an FFT and an inverse FFT to get the data that I'm looking for, but I'm fair
    ly inexperienced with using labVIEW and can't quite get it to work.
    Thanks for the help,
    Hank.

    As you may already know, in the Functions palette/Analysis VIs/Filters VIs are VIs for filtering. There are also some examples for using these filters under Examples/Analysis/fltrxmpl. You may find some of these are related to your situation, especially for filtering out the higher values.
    An option is to simply output the random values to a Comparison/"less than or equal" function, where only values <= to 100 would be sent to an array which is in a For loop. Use the iteration counter of the For loop to count up to 250, at which time you would pass the whole array to your next node. This would let you have 250 values between 0 and 100 for your final array.
    Good luck.

  • HELP creating random rectangle

    hi im having trouble it seems like my code is down correct but that isnt the case because i get 4 errors all involving 'MyRectangle' i get 4 cannot find symbol if ne one knows please help me out thanks my code is below thank you
    import java.awt.*;
    import java.awt.event.*;
    import java.util.ArrayList;
    import java.util.Iterator;
    import java.util.Random;
    import javax.swing.*;
    public class DrawJPanel extends JPanel
       // Random object to create random numbers
       private Random randomNumber = new Random();
       // Timer object to generate events
       private Timer drawTimer;
       // ArrayList object to hold MyRectangle objects
       private ArrayList rectangleArrayList = new ArrayList();
       // array of possible MyRectangle colors
       private Color[] colors = { Color.BLUE, Color.ORANGE, Color.PINK,
          Color.CYAN, Color.MAGENTA, Color.YELLOW, Color.BLACK,
          Color.WHITE, Color.RED, Color.GREEN };
       // no-argument constructor
       public DrawJPanel()
          super();
          drawTimer = new Timer( 250,
             new ActionListener() // anonymous inner class
                // event handler called every 250 microseconds
                public void actionPerformed( ActionEvent event )
                   drawTimerActionPerformed();  
             } // end anonymous inner class
          ); // end call to new Timer
          drawTimer.start(); // start timer
       }  // end contructor
       // create new MyRectangle object and add it to rectangleArrayList
       private void drawTimerActionPerformed()
          // get random dimensions and a random color
          int x = randomNumber.nextInt( 380 );
          int y = randomNumber.nextInt( 380 );
          int width = randomNumber.nextInt( 150 );
          int height = randomNumber.nextInt( 150 );
          int color = randomNumber.nextInt( 10 );
          // create MyRectangle object and add it to rectangleArrayList
          MyRectangle rectangle = new MyRectangle(x,y,width,height,colors[color]);
          rectangleArrayList.add( rectangle );
          repaint();
       } // end method drawTimerActionPerformed
       // draw all rectangles
       public void paintComponent( Graphics g )
          super.paintComponent( g );
          // create iterator
          Iterator rectangleIterator = rectangleArrayList.iterator();
          MyRectangle currentRectangle; // create MyRectangle
          // iterate through ArrayList and draw all MyRectangles
          while ( rectangleIterator.hasNext() )
             currentRectangle =
                ( MyRectangle ) rectangleIterator.next();
             currentRectangle.draw( g ); // draw rectangle
       } // end method paintComponent
       // clear rectangleArray
       public void clear()
          rectangleArrayList.clear(); // clear ArrayList
          repaint(); // repaint JPanel
       } // end method clear
    } // end class DrawJPanel

    And...?
    MyRectangle is not part of the Java API. So that means you wrote it... or something like that. Did you write a MyRectangle class?

  • Image loading and random numbers?

    Hi. I'm programming a text-based RPG using Swing.
    But I have two things to hamper my progress:
    1) I can't create random numbers
    2)I can't put images onto my window.
    Can anyone tell me a method to use do do these two things? Thanks.

    Hi. I'm programming a text-based RPG using Swing.
    But I have two things to hamper my progress:
    1) I can't create random numbersSee java.util.Random
    2)I can't put images onto my window.See Graphics.drawImage
    >
    Can anyone tell me a method to use do do these two
    things? Thanks.

  • How can I create random teams of 2 using numbers on an iPad?

    I am trying to create random teams of two for a card tournament. Can this be done using numbers on my iPad?

    Here's a solution using Numbers '09. If the functions used are supported in Numbers for iOS, it should work there, too. If not, try reposting in the iWork For iOS community.
    Column A of Players contains the names of the players entered in the tournament, in whatever order is convenient.
    Column B, which may be hidden, contains the same formula in all cells (except the header cell):
    =RAND()
    The formula generates a random number between zero and one.
    Column A of Teams contains team identifiers. These are text values. they play no part in determining the team selections.
    Columns B and C contain similar formulas:
    B2: =LOOKUP(SMALL(Players :: $B,2*(ROW()-1)-1),Players :: $B,Players :: $A)
    C2: =LOOKUP(SMALL(Players :: $B,2*(ROW()-1)   ),Players :: $B,Players :: $A)
    These formulas select the players in order of the random numbers in column B of Players. The players corresponding to the smallest, third smallest, fifth smallest...numbers are listed in column B, those corresponding to the second smallest, fourth smallest, sixth smallest... are listed in column C.
    The checkbox in Players::A1 is used as a trigger to spur recalculation of the tables and reordering of the teams. Clicking the checkbox toggles the value of that cell between TRUE and FALSE. Any change in a value in a Numbers table causes the table to be recalculated, which reselects the teams.
    Regards,
    Barry

  • Create a congruential random numbers

    I want to create a congruential random numbers generator in java:
    Below is the formula for it.
    ri+1=(a*ri+b) mod M .
    How can I use Math class for this?

    Your guess w.r.t. a and b being constants is right. An ordinary multiple congruence random number
    generator simply looks as you described:
    x[n+1]= (a*x[n]+b)%M
    But there's a bit more to it: a and b have to be relatively prime, i.e. gcd(a, b) == 1 and the same counts
    for both a and b w.r.t. M, i.e. gcd(a, M) == 1 and gcd(b, M) == 1. Only then the 'cycle length' of your
    generator will be maximal. In practice M is a power of two (2^32 comes to mind). Here's some code:public class MGRNG {
       private int a, b, M;
       private int seed;
       // ctors
       MGRNG(int a, int b, int M) { this(a, b, M, 1); }
       MGRNG(int a, int b, int M, int seed) {
          this.a= a;
          this.b= b;
          this.M= M;
          this.seed= seed;
       // next pseudo random number
       public int next() {
          seed= (a*seed+b)%M;
          return seed;
    } kind regards,
    Jos

  • Creating x random numbers that add up to a certain number

    How would I go about creating 3 random numbers from x - y that add up to a certain number.
    Or how would i create a set of numbers that are random but not repeating.

    How would I go about creating 3 random numbers fromx
    - y that add up to a certain number.Create 2 random numbers. Number 3 = certain
    number - (random number 1 + random number 2)
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Rand
    om.html
    Or how would i create a set of numbers that are
    random but not repeating.Create a List and fill it with numbers 1 - n. Shuffle
    the list with the Collections.shuffle(...) method.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Coll
    ections.htmlOr use a Set instead of a List, since Sets do not contain duplicates.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Set.html
    ? {?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • I need help with this program ( Calculating Pi using random numbers)

    hi
    please understand that I am not trying to ask anymore to do this hw for me. I am new to java and working on the assignment. below is the specification of this program:
    Calculate PI using Random Numbers
    In geometry the ratio of the circumference of a circle to its diameter is known as �. The value of � can be estimated from an infinite series of the form:
    � / 4 = 1 - (1/3) + (1/5) - (1/7) + (1/9) - (1/11) + ...
    There is another novel approach to calculate �. Imagine that you have a dart board that is 2 units square. It inscribes a circle of unit radius. The center of the circle coincides with the center of the square. Now imagine that you throw darts at that dart board randomly. Then the ratio of the number of darts that fall within the circle to the total number of darts thrown is the same as the ratio of the area of the circle to the area of the square dart board. The area of a circle with unit radius is just � square unit. The area of the dart board is 4 square units. The ratio of the area of the circle to the area of the square is � / 4.
    To simuluate the throwing of darts we will use a random number generator. The Math class has a random() method that can be used. This method returns random numbers between 0.0 (inclusive) to 1.0 (exclusive). There is an even better random number generator that is provided the Random class. We will first create a Random object called randomGen. This random number generator needs a seed to get started. We will read the time from the System clock and use that as our seed.
    Random randomGen = new Random ( System.currentTimeMillis() );
    Imagine that the square dart board has a coordinate system attached to it. The upper right corner has coordinates ( 1.0, 1.0) and the lower left corner has coordinates ( -1.0, -1.0 ). It has sides that are 2 units long and its center (as well as the center of the inscribed circle) is at the origin.
    A random point inside the dart board can be specified by its x and y coordinates. These values are generated using the random number generator. There is a method nextDouble() that will return a double between 0.0 (inclusive) and 1.0 (exclusive). But we need random numbers between -1.0 and +1.0. The way we achieve that is:
    double xPos = (randomGen.nextDouble()) * 2 - 1.0;
    double yPos = (randomGen.nextDouble()) * 2 - 1.0;
    To determine if a point is inside the circle its distance from the center of the circle must be less than the radius of the circle. The distance of a point with coordinates ( xPos, yPos ) from the center is Math.sqrt ( xPos * xPos + yPos * yPos ). The radius of the circle is 1 unit.
    The class that you will be writing will be called CalculatePI. It will have the following structure:
    import java.util.*;
    public class CalculatePI
    public static boolean isInside ( double xPos, double yPos )
    public static double computePI ( int numThrows )
    public static void main ( String[] args )
    In your method main() you want to experiment and see if the accuracy of PI increases with the number of throws on the dartboard. You will compare your result with the value given by Math.PI. The quantity Difference in the output is your calculated value of PI minus Math.PI. Use the following number of throws to run your experiment - 100, 1000, 10,000, and 100,000. You will call the method computePI() with these numbers as input parameters. Your output will be of the following form:
    Computation of PI using Random Numbers
    Number of throws = 100, Computed PI = ..., Difference = ...
    Number of throws = 1000, Computed PI = ..., Difference = ...
    Number of throws = 10000, Computed PI = ..., Difference = ...
    Number of throws = 100000, Computed PI = ..., Difference = ...
    * Difference = Computed PI - Math.PI
    In the method computePI() you will simulate the throw of a dart by generating random numbers for the x and y coordinates. You will call the method isInside() to determine if the point is inside the circle or not. This you will do as many times as specified by the number of throws. You will keep a count of the number of times a dart landed inside the circle. That figure divided by the total number of throws is the ratio � / 4. The method computePI() will return the computed value of PI.
    and below is what i have so far:
    import java.util.*;
    public class CalculatePI
      public static boolean isInside ( double xPos, double yPos )
         double distance = Math.sqrt( xPos * xPos + yPos * yPos );        
      public static double computePI ( int numThrows )
        Random randomGen = new Random ( System.currentTimeMillis() );
        double xPos = (randomGen.nextDouble()) * 2 - 1.0;
        double yPos = (randomGen.nextDouble()) * 2 - 1.0;
        int hits = 0;
        int darts = 0;
        int i = 0;
        int areaSquare = 4 ;
        while (i <= numThrows)
            if (distance< 1)
                hits = hits + 1;
            if (distance <= areaSquare)
                darts = darts + 1;
            double PI = 4 * ( hits / darts );       
            i = i+1;
      public static void main ( String[] args )
        Scanner sc = new Scanner (System.in);
        System.out.print ("Enter number of throws:");
        int numThrows = sc.nextInt();
        double Difference = PI - Math.PI;
        System.out.println ("Number of throws = " + numThrows + ", Computed PI = " + PI + ", Difference = " + difference );       
    }when I tried to compile it says "cannot find variable 'distance' " in the while loop. but i thought i already declare that variable in the above method. Please give me some ideas to solve this problem and please check my program to see if there is any other mistakes.
    Thanks a lot.

    You've declared a local variable, distance, in the method isInside(). The scope of this variable is limited to the method in which it is declared. There is no declaration for distance in computePI() and that is why the compiler gives you an error.
    I won't check your entire program but I did notice that isInside() is declared to be a boolean method but doesn't return anything, let alone a boolean value. In fact, it doesn't even compute a boolean value.

  • Problem with Purchase Order creation with Random numbers .

    Hi Experts
    Currently i am facing an issue with Bapi BAPI_PO_CREATE1 to create Purchase order with random numbers for example items 1, 3,5.
    Please let me know the settings .
    Thanks in Advance

    Hi Neha,
    A reset of the release strategy only takes place if
    -  the changeability of the release indicator is set to '4' in
       case of a purchase requisition and '4' or '6' in case of
       another purchasing document (purchase order, request for
       quotation, contract, scheduling agreement),
    -  the document is still subject to the previous release
       strategy,
    -  the new TOTAL NET ORDER VALUE is higher than the old one.
    The total net order value is linked to CEKKO-GNETW for a purchase order,
    CEBAN-GSWRT for a purchase requisition item-wise release and CEBAN-GFWRT
    for a purchase requisition overall release.
    If you have maintained a Tolerance for value changes during release
    (V_161S-TLFAE), the release strategy is reset when the value of the
    document is higher than the percentage you have specified and if the
    document is still subject to the previous release strategy.
    Review the SAP note 365604 and 493900 for more
    information about Release strategy.
    Regards,
    Ashwini.

  • Random numbers in a table

    I'm new to java, so please bear with me. What I want to do is create a program which chooses random numbers (between 0-9) in a table, and then presents a diagram of how many of each number comes up.
    e.g. if the table size was 10, the output could be something like:
    0 *
    1 **
    2
    3 *
    9 **
    with the stars representing the number of times the number showed up. Any assistance you could provide would be great and appreciated. Thank you

    1) Create a Map. The key will be one of the random numbers, the value will be a counter of the number of times the number has been stored.
    2) Generate a random number.
    3) Place the random number in the map key, and increment the value.
    4)Print the random numbers and as many asterisks as the counter values.
    I believe this is classwork? Asking about problems in the code that are not working is ok - asking people to write sample code for you is not ok. Part of the assignment requires you to read the documentation and figure out how to write the code.

  • Help in generating the same random numbers at every time of executuion

    dear friends
    i am facing a problem that the random numbers generated at time of each exectuion of the program are not the same, i want to generate the same random numbers every time time i run the program. i need your help. i am giving the code in c++ if anybody can help in providing the solution so that i get the same random numbers at every run of the program. waiting for your help
    wit regards
    jaya shankar
    #include<iostream.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<time.h>
    #include<math.h>
    class density
    int s[150][150],parent[150][150],i,j,l,n,loop;
    public:
    void bd(void);
    void css(void);
    void density :: bd(void)
    cout<<"ENTER THE POPULATION SIZE = ";
    cin>>n;
    cout<<"\nENTER THE NO.OF LOOPS = ";
    cin>>loop;
    for(i=0;i<n;i++)
    for(j=0;j<80;j++)
    s[j]=rand()%2;
    cout<<"s:"<<s[j];
    void density :: css(void)
    int a,b;
    float c;
    for(i=0;i<n;i=i+2)
    b=rand()%100;
    cout<<"random b="<<b;
    main()
    density d;
    d.bd();
    d.css();

    You have to read the documentation for the java.util.Random class.
    "If two instances of Random are created with the same seed, and the same sequence of method calls is made for each, they will generate and return identical sequences of numbers. In order to guarantee this property, particular algorithms are specified for the class Random"
    Here is a peace of code that will do wat you need:
    Random rand = new Random(100);
    for(int i=0; i<10; i++)
         System.out.println("Random="+ rand.nextInt(10));

  • Random Numbers with Objective-C

    Hey Guys,
    I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
    I know I can use the following to generate a number between 1-52, but I need the to eliminate the possibility of the same card being drawn twice:
    cardNumber = arc4random() % 52 + 1;
    Any idea on how I would do this? Code example would be helpful!
    Thanks,
    Justin

    Hi Justin -
    Justin Carman wrote:
    I'm creating a blackjack program and I need to randomize 52 numbers, ensuring not to repeat any number.
    I would initialize an array (the deck) with the card values, then use your random number as the index into the array. Each time a card is chosen just remove its value from the deck and decrement the modulus of the random numbers. NSMutableArray makes a nice deck for this purpose since its count is automatically decremented each time a value is removed. E.g.:
    // AppController.m
    #import "AppController.h"
    #define N_DECK 52
    @implementation AppController
    @synthesize cardArray; // @property (nonatomic, retain) NSMutableArray *cardArray;
    - (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    self.cardArray = [NSMutableArray arrayWithCapacity:N_DECK];
    - (IBAction)newDeck:(id)sender {
    [cardArray removeAllObjects];
    for (int i = 0; i < N_DECK; i++) {
    [cardArray addObject:[NSNumber numberWithInt:i+1]];
    // NSLog(@"newDeck: cardArray=%@", cardArray);
    - (IBAction)getCard:(id)sender {
    // check the array
    int count = [cardArray count];
    assert(count <= N_DECK);
    if (count < 1) {
    NSLog(@"getCard: Empty deck");
    return;
    NSLog(@"getCard: count=%d", count);
    // select a card from the array
    int index = arc4random() % count;
    NSNumber *selected = [cardArray objectAtIndex:index];
    NSLog(@"getCard: index=%d selected=%@", index, selected);
    // print the value of the selected card
    int card = [selected intValue];
    NSLog(@"getCard: card=%d", card);
    // remove the selected card from the array
    [cardArray removeObjectAtIndex:index];
    // note selected NSNumber object has been released
    // NSLog(@"getCard: cardArray=%@", cardArray);
    @end
    For extra credit you might want to wrap the above in a custom Deck class.
    Hope that helps!
    - Ray

  • Also Question about create Random number

    What's the best way to create random number in main method, which will allow the number (random) to be stored into content of queue. I was thinking somewhere along the road, is this the appropriate way to handle this?
    import java.util.*;
    public static void main(String[] args)
            Queue q=new Queue();
    Random random = new Random ();
            for(int i=0;i<12;i++)
               q.add(random);
              

    Close, but not quite. That will add the same random number number generator (no random numbers) to the queue 20 times.
    Look at the methods in the Random class to find the one that suits your needs for using the generator (the Random) to generate a random number.
    http://java.sun.com/j2se/1.5.0/docs/api/java/util/Random.html

Maybe you are looking for

  • Unable to access localhost from network

    I can not access main page from other computers of the network. the ip of main computer is http://192.168.1.8:5050/examples/servlets/index.htmlwhen i put in connection specs of my browser then i can see it but unable to interact with database as mess

  • Help can not download itunes 7, keep getting message saying

    HKEY-LOCAL-MACHINE\SOFTWARE\CLASSES\QUICKTIMEPLAYERLIB.QUICKTIMEPLAYERAPP\CLSID. VERIFY THAT YOU HAVE ACCESS TO THAT KEY? WHAT!HAVE TRIED CALLING APPLE CAN NOT HEAR A WORD THEY SAY, ANY IDEAS ANY ONE I AM GOING MAD HELP!   Windows XP  

  • Background processing of Program

    Hi all, I have a requirement of background processing of a program which is called from another program. Requirement : during execution of Program A, Program B is Submitted to run in background with two field values from Program A. Is it possible ? I

  • Why is my exported movie cropped?

    When I export my movie project to Quicktime movie (or to mp4), it is cropped as if a widescreen mask had been applied, although the project properties confirm it's a standard 4:3. The project looks fine in iMovie's canvas. I was wondering if anyone k

  • Raise exception using CX_MAPPING_FAULT

    Hi, I want to raise an exception when an error occured in the ABAP mapping.I can be able to raise single message exception using the above one but I want to raise exception for all the messages from an error message internal table.I collect return co