How to generate unique random numbers

Hi All,
I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
Random diceRoller = new Random();
for (int i = 0; i < 10; i++) {
  int roll = diceRoller.nextInt(6) + 1;
  System.out.println(roll);
}My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
Using the above example to illustrate my intention:
1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
Any assistance would be much appreciated.
Many thanks,
Jack

htran_888 wrote:
Hi All,
I am wondering whether there is already a random library or built-in function available in Java to produce some random numbers between certain ranges that are not repetitive. Let's look at a common examples as follows:
Random diceRoller = new Random();
for (int i = 0; i < 10; i++) {
int roll = diceRoller.nextInt(6) + 1;
System.out.println(roll);
}My understanding from this approach is that it allows the same number to be repeated over and over again. However, I would like to find out how to continue generating random numbers from remaining ones that haven't been generated earlier.
Using the above example to illustrate my intention:
1st random number generated - possibility of 1 - 6 showed up. Say 5 is picked.
2nd random number generated - possibility of 1, 2, 3, 4, 6 only. Say 2 is picked.
3rd random number generated - possibility of 1, 3, 4, 6 available. Say 1 is picked.
4th random number generated - possibility of 3, 4, 6 left. Say 6 is picked.
5th random number generated - possibility of 3, 4 remains. Say 4 is picked.
Any assistance would be much appreciated.If it is your school assignment then you have the answer above (List & the lists length).
(You might want to look at Collections)

Similar Messages

  • How to generate sepecific serial numbers?

    We want to generate specific serial number for item from paraemters, don't want to use the prefix or start number of item attribute.
    Serial Number should generated not associated with transactions. And Item attribute defined as "PRE-DEFINDED"
    And we do not want to insert basis table MTL_SERIAL_NUMBERS.
    We need API or Interface to do this.
    Is there anyone can help me?

    randy_ortan wrote:
    How to generate unique random numbers with out repetitions.The simplest way is to load the numbers 1 to 9 into an ArrayList. Then you use the Collections.shuffle method to shuffle the ArrayList numbers into random order. Finally you pick the 5 first numbers in the ArrayList. They will be unique and randomly picked from the 1 to 9 interval.
    If you want another 5 numbers you just reshuffle the ArrayList and pick the 5 first numbers again.

  • Unique Random numbers

    How to get unique random numbers every time in AS3
    I have searched but not able to get satisfactory results

    var rand :Number;
    rand = Number(movXml.movie.length());
    for(var n:uint = 0 ; n<5 ; n++)
    num1 = Number(Math.round(Math.random()* ((rand-1) - 0) + 0 ) );
    if(tempArray.indexOf(num1) == -1)
    tempArray.push(num1);
    //trace(tempArray);
    num2  = Number (tempArray[0]);
    //trace("num1:"+num2);
    trace(tempArray);
    some time this produce more than 5 numbers
    and some time less than 3
    I want 4 random numbers , but different
    the above loop runs 4 times , so if number is repeated , it will not add to Array , hence i will not able to get 4 Required numbers

  • How can I generate multiple unique random numbers?

    Hello,
    I am trying to generate multiple random numbers between a given set of numbers (1-52) and not have the same number generated twice within that set. I can compare the last and next numbers with the compare function but how would I go about comparing all of the generated numbers without using a huge list of shift registers...
    Any help/ideas are welcome and appreciated.
    Jason
    Solved!
    Go to Solution.

    Here is an implementation of Jason's solution.
    steve
    Help the forum when you get help. Click the "Solution?" icon on the reply that answers your
    question. Give "Kudos" to replies that help.
    Attachments:
    random.vi ‏10 KB

  • Generate the random numbers

    How Do I Generate Random Numbers in iWorks
    Excel has the "F9" key to generate random numbers numbers don't
    please see below what i'm trying to do
    I open up a blank Excel worksheet, and type the number "1" into cell A1. Type the number "2" into cell A2. Then type the number "3" into cell A3. Type the number "4" into cell A4, and then type the number "5" into cell A5.
    2
    Type the word "PB" into cell A6.
    3
    Enter the function "=RANDBETWEEN(1,59)" into cell B1.
    4
    Enter an exact copy of this function "=RANDBETWEEN(1,59)" into cells B2, B3, B4, and B5.
    5
    Enter the function "=RANDBETWEEN(1,39)" into cell B6.
    6
    Hit the "F9" key to generate the random numbers simulating game.
    But in numbers how do i do this?
    Thanks!
    Alex...

    firstly your not asking about generating random numbers, your asking how do you make a workbook recalculate new random numbers. From M$'s website:
    F9
    Calculates all worksheets in all open workbooks
    It does not produce random numbers the equations should produce random numbers as soon as you enter them in. If they dont then you have automatic reclaculations turned off and F9 is forcing a recalc.
    In numbers there is not shortcut to forcing the workbook to recalculate other than enter data into a cell. So if you made a new table and then enter data. For every data point you enter you should see new data apear.
    Was just validating the method for forcing and its not working on my ipad. I will mark this conversation and if i find it i will respond again.
    Jason
    Message was edited by: jaxjason

  • Generate multiple random numbers?

    Hi,
    I'm trying to generate random numbers using Math.random()* n;
    but I want the random numbers to reset to something different after
    a particular event is called. Instead, I've noticed the numbers
    either buzz away randomly in every frame (when placed inside
    onEnterFrame), or it picks random numbers once, and then uses those
    same values over and over (when placed outside the onEnterFrame).
    How do i get actionscript to generate new random numbers
    after each myMC.onPress = function(), or alternatively, after a
    score changes (like some kind of watch feature?)

    ok, i've got a half working version;
    function ranbot(x) {
    return Math.ceil(Math.random()* x) + "/" +
    Math.ceil(Math.random()* x);
    trace(ranbot(60));
    but is it possible to set up the function so the numerator is
    equal to or less than the denominator? Also, if the numerator is
    set to never exceed the denominator, then a large percentage -
    something like 25-50% of the output fractions would equal "1", like
    55/55, 23/23, 7/7, 28/28, and so on.
    I did something like this when using variables;
    var randombot2:Number = Math.ceil(Math.random()* 99);
    var randomtop2:Number = Math.min(randombot2 -
    Math.floor(Math.random()* randombot2* 0.5),
    Math.ceil(Math.random()* 99));
    - but I do not understand how this works in function
    terminology.

  • Array of unique random numbers - help?

    basically, i'm trying to create a BINGO card.
    i stared learning Java a week ago and am finding it easy to learn and use....at least so far.
    my instructor gave me the assignment to created a BINGO card. so i used the system.out.format command to make 5 tab fields, 8 spaces each ("%8s %8s %8s %8s %8s", "B", "I", "N", "G", "O"). although the assignment only wanted me to think numbers out of thin air, just to use as examples, i went above and beyond with the idea to make a BINGO card generator that could actually function.
    then i started the random number sequences, using the Math.random() command. all told, there are 24 of these in the program, one for each number on a bingo card. the field in the middle is the FREE space, so it has no Math.random command.
    in BINGO, each letter (one of my five tab fields) can have a number in ranges of 15. B is 1 to 15, I is 16 to 30, etc. it looks similar to this:
    B I N G O
    9 19 39 57 66
    3 28 32 51 74
    3 29 FREE 46 70
    14 28 43 55 67
    9 24 35 59 62
    as you can tell, i'm having trouble with actually making unique random numbers so that none repeat.
    is there a command or string or something to help me accomplish this?

    The best way I've come up with is to use an object to store the numbers that implements Collection--like ArrayList...
    Then you load it with the range of numbers that you want and call, shuffle() on the object, that will randomize your range of numbers and then you can choose the quantity you want from the storage object. So let's say you need 25 number in the range of 1 to 100:
    Add the numbers (you have to use classes so I would do Integers) 1 to 100;
    call shuffle()
    pull back the first 25 numbers
    This will guarantee that each number is distinct and in a random order.
    If you need multiple sheets populated, you can just call shuffle() between population of each sheet.
    package Junk;
    import java.util.ArrayList;
    import java.util.Collections;
    class Junk{
      private ArrayList<Integer> l;
      Junk(){
        l = new ArrayList<Integer>();
      public void loadList(int s, int e){
        for(int i=s; i<=e; i++){
          l.add(new Integer(i));
      public void randomizeList(){
        Collections.shuffle(l);
      public void printList5(){
        for(int i=0; i<5; i++){
          System.out.println(l.get(i));
      public static void main(String[] args){
        Junk j = new Junk();
        j.loadList(10,99);
        j.randomizeList();
        j.printList5();
        System.out.println();
        j.randomizeList();
        j.printList5();
    }

  • Urgent How to generate a random code such as registration code?

    I would like to ask that how to generate a random code?
    For example, when you register a E-mail account, you need to enter the code for activation. I would like to create a java Bean to do this job. Would you help me?

    In fact, I would like to set a 10 digi codes randomly (such as FH654CS081, MKO624VG9f) for user input when they register the forum account. This random code will be sent to the user's email. User have to input this code to a JSP web site. Also, the code which is inputed by user will be matched with the database. If user input success, the forum account will be activated.
    By generating this 10 digi codes, I want to handle this generation by using java bean.
    1) Any thing else i need to import ? (such as <% page import="java.......?")
    2) Any functions can handle this task?
    3) Any example can be my reference?
    Thank you very much

  • How to generate a random session variable in php

    i want to generate a random session variable and insert the variable in a mysql record to use later to validate an account set up.
    person fills out form to create account and submits; inserts form information in mysql record.
    i want the random variable to be inserted from a hidden field and the page sends an email with a link to click on to compare the variable to validate the user.
    Not sure how to generate a random session variable and get that to the hidden field value to be inserted with the other form information.
    thanks for your help,
    Jim Balthrop

    To insert the key I would personally do something like...
    $key = md5($username . $password . $salt);
    Insert that into your MySQL database, then send them a email with it, my next code shows how to activate it.
    This is to activate the account.
    <?php
    $key;
    $errors = array();
    if(isset($_GET['key']){
         $key = $_GET['key'];
         $sql = 'SELECT * FROM users WHERE key = \'' . $key '\' LIMIT 1';
         $result = mysql_query($sql) or die(mysql_error());
         if(mysql_num_rows($result)){
              $sql2 = 'UPDATE users SET active = 1 WHERE key = \'' . $key '\' LIMIT 1';
              $result2 = mysql_query($sql2) or die(mysql_error());
              if($result2){
                   //successfully activated account
              else{
                   //Something Went Wrong!
         else{
              $errors[] = 'Invaild Key, Please try again!';
    else{
         $errors[] = 'Invaild Key, Please try again!';
    ?>

  • How can you generate Multiple random numbers from 1 to 49?

    I am very new at programming with the iPhone SDK and I need some help with a project I am working on. What I want to do is set up a window with 6 labels and 1 button. When the user clicks the button, the program will populate 6 randomized numbers each ranging from 1 to 49, and then place each of 6 numbers in a label. But each time the program ends and starts again the numbers cannot be the same, and also when the user clicks the button, no label can have the same number twice, so for example. If label 1 had the number 10, the other 5 labels cannot have that number until the button is clicked again. I know how to set up the interface, I just need the code. I would so greatly appreciate someone's help in this matter. I have been trying to do this for days and I cannot figure it out. Possibly someone who knows tons about Objective C programming can help me!
    Thank-you so very much!!

    I see that you're writing a lottery number generator. Perhaps the easiest way to do it is to emulate a real lottery: fill an array (NSMutableArray, probably) with the numbers between 1 and 49, pick one at random, remove that number from the array, and repeat. (You can think of the numbers as being the balls and the array as being the machine that pops them out.)
    One simple way to get the random indices needed is to extract six random bytes from Randomization Services using SecRandomCopyBytes, then loop over them, using the modulo operator (%) to select an index within the size of the array.
    And no, I'm not going to write your code for you. If I was going to do that, I could package and sell the app myself.

  • How to generate unique numbers

    hi all,
    I want to generate unique numbers always starting from 1 using a single sql query and I dont want to use a sequence and i dont think rownum will be helpful for generating unique numbers in all cases . how to do this ?
    thanks & regards,
    kumar.

    If two users get the MAX from temp, they would be updating with the same value for two different rows.If TEMP is a genuine temporary table, this is not an issue, because the data in a temporary table is only visible within a session.
    The big problem with this approach is the mutating table one: we cannot issue the requisite select statement from a BEFORE INSERT trigger. So this solution is only going to work with a view and an INSTEAD OF INSERT trigger.
    Another, more workable, solution is to use a code control table. This can be (should be) another temporary table, with one row holding one column - next value for TEMP.ID. Normally we would rule out such a solution because it serializes access to the inserted table, but as this is only on a per session basis, it doesn't matter.
    CREATE OR REPLACE TRIGGER tmp_bir BEFORE INSERT ON temp1 FOR EACH ROW
    DECLARE
      ln NUMBER;
    BEGIN
      SELECT nvl(code1.next_id,1) INTO ln
      FROM code1;
      :NEW.id := ln;
      UPDATE code1
      SET    next_id := ln+1;
    END;Beware: coded freehand, so may need debugging.
    Cheers, APC

  • How do you generate multiple random numbers between 1 and 49

    I am new at mac programming and I want to make an iPhone app with the free SDK. What I would like to try is a random number generator. I imagine it as when the user clicks a button 6 random numbers from 1 to 49 would appear in a label or another control. If someone could please give me the code that would place these randomized numbers in a label I would greatly appreciate it. I know how to link all the controls together, I just need the code. Thank-you to anyone that can help!

    semi-sudo code goes here
    --prepare and array which will have number from 0 to 49
    --loop thru the array like this
    int i=0
    for (i; i<=49; i++) {
    int a=arc4random() % 49] ;
    int b=arc4random() % 49];
    --here exchange the objects so that they are shuffled
    [myArray exchangeObjectAtIndex:a withObjectAtIndex:b];

  • 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

  • How to generate a random number with at least 6 digits?

    Hi all,
    All is in the question. :-)
    I would like to generate a random number but the function "random
    number" in Labview isn't accurate enough.
    Do you know an algorithm to generate a random number of 6 or more
    digit?
    Thanks,
    PF

    Hi PF,
    It's simple. Use 2 random number functions in the same process. Now you
    should have 2 distinct random numbers that have the same accuracy. Let's say
    LV gives accuracy up to the thousandth (0.XXX), now if you divide one number
    by 1000 and then add to the other number you should then have something like
    0.XXXXXX. Actually, LV random number function can give up to about 17 digits
    (decimal). If you are looking for more digits (>17 digits), the idea above
    may not work, then the last thing you may want try is to generate two or
    three random numbers then convert all these decimal numbers to fractional
    strings chop off the 0 and dot then concatinate them together. After all
    it's still a random number. How many digits do you want to get? Make sure
    the indicators acce
    pt that many digits?
    Good luck
    Louis.
    P-F wrote in message
    news:[email protected]..
    > Hi all,
    >
    > All is in the question. :-)
    >
    > I would like to generate a random number but the function "random
    > number" in Labview isn't accurate enough.
    >
    > Do you know an algorithm to generate a random number of 6 or more
    > digit?
    >
    > Thanks,
    >
    > PF

  • How to generate pseudo random noise(PRN) binary sequence using shift registers?

    what is the block diagram to generate pseudo random noise (PRN) binary sequence of 1's and 0's using shift registers
    please help
     i need 2 submit this project in this week

    This is a fairly simple homework problem. My hints (on the LabVIEW side):
    1- look at while loops
    2- look at shift registers on while loops with multiple input elements
    3-look at the logic components, AND, OR XOR
    Look at this wiki article: http://en.wikipedia.org/wiki/Linear_feedback_shift_register
    Do the work, you won't learn if someone shows you how it is done! The palette that the previous post points to are of PRN and other "noise generators" but I suspect that is not what you are after.
    Know that creating a PRN with a reasonable number of shift register taps produces very pseudo results, as the "random" pattern begins to repeat pretty quickly, thereby making it not a truly random number. 
    When you have an attempt that is sort of working and want additional suggestions, post the code here. We won't do your work, we will help you try to do it, and learn it, yourself.
    Putnam
    Certified LabVIEW Developer
    Senior Test Engineer
    Currently using LV 6.1-LabVIEW 2012, RT8.5
    LabVIEW Champion

Maybe you are looking for

  • Portal Forms are not displayed in the new migrated environment.

    Hi All, We have a distributed Portal environment. Application server and Portal Repository running on one system(System1) and one more portal repository and portal components existing in anothor system(System2). Through DAD we connect to System2 and

  • Project Material

    Hi I need to make out report based on some non sap fields. How can i link PO# with Project order #? I need PO,Material code,vendor and vendor name,Item,order quantity,Project order,Project order desc etc. Can anyone suggest me any standard tcode,I ha

  • Order of af:resource

    I have 2 javascript imports using af:resource in my page. We'll call them a.js and b.js. The b.js has dependencies on the a.js so I declared the af:resource for a.js first then followed by b.js. Oddly enough the actual order of <script> tags in the g

  • Error while installting Oracle 9iAS Infrastructure on WIN XP

    Hi all I'm getting the "Database Configuration Assistant failed" error while installing Oracle 9iAS rel2 on Windows XP. How can I rectify this problem on Windows??..Metalink gives a troubleshooting strategy on Unix but not for windows... Please anyon

  • Apple Mail trouble sending messages

    I added my Slippery Rock University account to the apple mail server and all of my messages showed up, but when I try to send an email it says there is something wrong with the server and it will not send. How can I fix this? All of the information I