6 random numbers without repeat

I'm trying to make a 6 digit random number generator between 1 and 48. When the user click a button 6 random numbers show up in 6 different textFeilds. The problem is that I don't want the same number twice. How can I generate 6 different random numbers without using return and breaking out of the function?
import flash.events.Event;
stop();
btn.addEventListener (MouseEvent.CLICK, random1);
function random1 (evt:Event) {
          display1.text = "";
          display2.text = "";
          display3.text = "";
          display4.text = "";
          display5.text = "";
          display6.text = "";
          var r1 = Math.floor(Math.random()*(1+48-1))+1;
          var r2 = Math.floor(Math.random()*(1+48-1))+1;
          var r3 = Math.floor(Math.random()*(1+48-1))+1;
          var r4 = Math.floor(Math.random()*(1+48-1))+1;
          var r5 = Math.floor(Math.random()*(1+48-1))+1;
          var r6 = Math.floor(Math.random()*(1+48-1))+1;
          if (r2 == r1 || r3 == r2 || r4 == r3 || r5 == r4 || r6 == r5) {
                    return;
          var liste:Array = new Array();
          liste.push(r1,r2,r3,r4,r5,r6);
          liste.sort(Array.NUMERIC);
          display1.text = String(liste[0]);
          display2.text = String(liste[1]);
          display3.text = String(liste[2]);
          display4.text = String(liste[3]);
          display5.text = String(liste[4]);
          display6.text = String(liste[5]);

Here's the code for the approach mentioned with your textfields included
btn.addEventListener (MouseEvent.CLICK, random1);
function random1 (evt:Event) {
    var nums:Array = new Array();
    // fill the array of numbers
    for(var i:uint=1; i<=48; i++){
        nums.push(i);
    shuffle(nums);
    // grab the first six in the shuffled array
    var liste:Array = nums.splice(0,6);
    // assign the values to the textfields
    for(var j:uint=1; j<=6; j++){
        this["display"+String(j)].text = String(liste[j]);
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;

Similar Messages

  • How do I generate random numbers from a list of numbers without repeating any number

    I am trying to generate a list of random numbers without any repeating numbers.  For example say the list is from 1 to 15, how do I randomly generate a list of numbers using each number only once?

    pb,
    You can build a randomizer by making a 2-column table with 15 rows. In Column A, Fill with the numbers 1 to 15. In column B Fill with RAND(). Then sort on Column B. There will now be a randomized list of the numbers from 1 to 15 in Column A. You can copy this random list and use it in your application.
    Jerry

  • Random numbers without duplicates

    Hello,
    I'm having trouble locating an explained example for selecting a set of random numbers without duplicates. Specifically, I'm working on this example from Ivor Horton's Beginning Java, chapter 3.
    3. A lottery program requires that you select six different numbers from the integers 1-49. Write a program to do this for you and generate five sets of entries.
    This is not homework, I'm just trying to teach myself Java to eventually work my way up to servlets and JSPs.
    This is what I have so far. I tried to use array sorting but it didn't work (the first three numbers in my entries was always 0), so I commented out that part. I've included sample output after the code. I don't necessarily need the exact code although that would be nice; I just need at least an explanation of how to go about making sure that if a number has been picked for an entry, not to pick it again.
    Thanks for any help,
    javahombre
    package model;
    import java.util.Random;
    import java.lang.Math.*;
    import java.util.Arrays;
    public class Lottery {
    public static void main(String[] args) {
    // Lottery example.
    // We need the following data:
    // - An integer to store the lottery number range (in this case 59).
    // - A mechanism to choose a number randomly from the range.
    // - An array to store the entries (6 different numbers per entry).
    // - A loop to generate 5 sets of entries.
    int numberRange = 59;
    int currentPick = 0;
    int[] entry = new int[6]; // For storing entries.
    //int slot = -1; // For searching entry array.
    Random rn = new Random();
    for (int n = 0; n < 5; n++)
    // Generate entry.
    for (int i = 0; i < 6; i++)
    currentPick = 1 + Math.abs(rn.nextInt()) % numberRange;
    //Arrays.sort(entry);
    //slot = Arrays.binarySearch(entry, currentPick);
    //System.out.println("i: " + i + "\t| slot: " + slot + "\t| pick: " + currentPick + "\t| compare: " + (slot < 0));
    // Add the current pick if it is not already in the entry.
    //if (slot < 0)
    entry[i] = currentPick;
    System.out.println("pick entered: " + currentPick);
    // Output entry.
    System.out.print("Entry " + (n + 1) + ": ");
    for (int j = 0; j < 6; j++)
    System.out.print(entry[j] + "\t");
    System.out.println("");
    // Set the array contents back to 0 for next entry.
    Arrays.fill(entry,0);
    Sample output (notice duplicates, as in Entry 3):
    pick entered: 11
    pick entered: 29
    pick entered: 33
    pick entered: 8
    pick entered: 14
    pick entered: 54
    Entry 1: 11     29     33     8     14     54     
    pick entered: 51
    pick entered: 46
    pick entered: 25
    pick entered: 30
    pick entered: 44
    pick entered: 22
    Entry 2: 51     46     25     30     44     22     
    pick entered: 49
    pick entered: 39
    pick entered: 9
    pick entered: 6
    pick entered: 46
    pick entered: 46
    Entry 3: 49     39     9     6     46     46     
    pick entered: 23
    pick entered: 26
    pick entered: 2
    pick entered: 21
    pick entered: 51
    pick entered: 32
    Entry 4: 23     26     2     21     51     32     
    pick entered: 27
    pick entered: 48
    pick entered: 19
    pick entered: 10
    pick entered: 8
    pick entered: 18
    Entry 5: 27     48     19     10     8     18     

    NOTE: the array reference to [ i ] seems to be misinterpreted as italics by the posting form. I've reposted the message here, hopefully it will show the code properly.
    Thanks again,
    javahombre
    Hello,
    I'm having trouble locating an explained example for
    selecting a set of random numbers without duplicates.
    Specifically, I'm working on this example from Ivor
    Horton's Beginning Java, chapter 3.
    3. A lottery program requires that you select six
    different numbers from the integers 1-49. Write a
    program to do this for you and generate five sets of
    entries.
    This is not homework, I'm just trying to teach myself
    Java to eventually work my way up to servlets and
    JSPs.
    This is what I have so far. I tried to use array
    sorting but it didn't work (the first three numbers in
    my entries was always 0), so I commented out that
    part. I've included sample output after the code. I
    don't necessarily need the exact code although that
    would be nice; I just need at least an explanation of
    how to go about making sure that if a number has been
    picked for an entry, not to pick it again.
    Thanks for any help,
    javahombre
    package model;
    import java.util.Random;
    import java.lang.Math.*;
    import java.util.Arrays;
    public class Lottery {
    public static void main(String[] args) {
    // Lottery example.
    // We need the following data:
    // - An integer to store the lottery number range (in
    this case 59).
    // - A mechanism to choose a number randomly from the
    range.
    // - An array to store the entries (6 different
    numbers per entry).
    // - A loop to generate 5 sets of entries.
    int numberRange = 59;
    int currentPick = 0;
    int[] entry = new int[6]; // For storing entries.
    //int slot = -1; // For searching entry
    array.
    Random rn = new Random();
    for (int n = 0; n < 5; n++)
    // Generate entry.
    for (int i = 0; i < 6; i++)
    currentPick = 1 + Math.abs(rn.nextInt()) %
    numberRange;
    //Arrays.sort(entry);
    //slot = Arrays.binarySearch(entry, currentPick);
    //System.out.println("i: " + i + "\t| slot: " + slot +
    "\t| pick: " + currentPick + "\t| compare: " + (slot <
    0));
    // Add the current pick if it is not already in the
    entry.
    //if (slot < 0)
    entry[ i ] = currentPick;
    System.out.println("pick entered: " + currentPick);
    // Output entry.
    System.out.print("Entry " + (n + 1) + ": ");
    for (int j = 0; j < 6; j++)
    System.out.print(entry[j] + "\t");
    System.out.println("");
    // Set the array contents back to 0 for next entry.
    Arrays.fill(entry,0);
    Sample output (notice duplicates, as in Entry 3):
    pick entered: 11
    pick entered: 29
    pick entered: 33
    pick entered: 8
    pick entered: 14
    pick entered: 54
    Entry 1: 11     29     33     8     14     54
    pick entered: 51
    pick entered: 46
    pick entered: 25
    pick entered: 30
    pick entered: 44
    pick entered: 22
    Entry 2: 51     46     25     30     44     22
    pick entered: 49
    pick entered: 39
    pick entered: 9
    pick entered: 6
    pick entered: 46
    pick entered: 46
    Entry 3: 49     39     9     6     46     46
    pick entered: 23
    pick entered: 26
    pick entered: 2
    pick entered: 21
    pick entered: 51
    pick entered: 32
    Entry 4: 23     26     2     21     51     32
    pick entered: 27
    pick entered: 48
    pick entered: 19
    pick entered: 10
    pick entered: 8
    pick entered: 18
    Entry 5: 27     48     19     10     8     18

  • Random numbers without using java funtions

    i need a formula to generate 100 random numbers 1-20
    any suggestions?

    Doesn't need much explaining. Did you try it?
    http://www.google.com/search?q=RNG+algorithms&sourceid=mozilla-search&start=0&start=0&ie=utf-8&oe=utf-8

  • Frame Random Shuffle without repeating

    Hi,
    Am beginning an eLearning project (I'm a retired social worker aiming in this lesson to help others) which includes building in AS3 an exercise called the GNAT (Go No/Go Association Task). The GNAT is a test tool that measures people's subconscious attiudes by having them choose (or not choose) by  pressing/touching the spacebar (in this lesson) when they see a specific target word.
    For the first part of the GNAT, a practice exercise: 16 target words (presented one each in its own frame), taken randomly with no repeats from a list or array of 18 words. Frame needs to time out in 1000 ms. If the person reacts by pressing/touching the spacebar when they see a word, it is either scored +1 (depends on the word) or nothing. If pressed, an X or 0 displays for 100 ms (wrong or correct, depending on the word) and then goes immediately to the next random (no repeat) frame and word. If not pressed the timer timeout at 1000 ms goes to the next random (no repeat) frame.
    Whew! For my relatively modest AS3 skills, not sure how to set up a model for this and implement in script. Could also be one dynamic text box in a single frame instead of multiple frames, with the text (target word) changing. But still would need a timer to advance and if pressed, an over-ride of the timer to advance, plus scoring.
    If I can get a basic model working, then I can try to build the main test exercise tool which has 9 target words but these are recycled randomly in a 3:6:3 ratio totaling 70.
    Major challenge!!!
    I've tried various random no repeats using frames but can't get the most basic version to work.
    I would appreciate any help getting started. How best to set this up and begin?
    Regards,
    saratogacoach

    Using frames is not likely to be relevant to what you seem to want to do.  One frame, one textfield, and code is all you should need.
    Just create the array, shuffle it, and pick the first 16 or whatever words in the shuffled array, one at a time as you advance thru the exercise.  If you want a function to shuffle the array you can find the same one often offered in this forum, such as here...
    http://forums.adobe.com/thread/1058786?tstart=0
    If you need help with setting up a Timer, you should not have a problem searching Google for a tutorial (use "AS3 Timer tutorial")

  • Random Generation without repeat

    Hi, I am trying to write a script that will generate a random 5 digit number, using only the digits 1, 2, 3, 4, & 5, and with no repeats. For example: 12345, or 31524, or 24153. At the moment I can make the random 5 digit number, using only the digits 1, 2, 3, 4, & 5, yet I am struggling to get no repeats. So far I have something along the lines of:
    set x to some item of "12345"
    set y to some item of "12345"
    set z to some item of "12345"
    set a to some item of "12345"
    set b to some item of "12345"
    if x = y then
    if x ≤ 1 then
    set x to x + 1
    end if
    if x ≥ 5 then
    set x to x - 1
    end if
    else if x = z then
    if x ≤ 1 then
    set x to x + 1
    end if
    if x ≥ 5 then
    set x to x - 1
    end if
    else if x = a then
    if x ≤ 1 then
    set x to x + 1
    end if
    if x ≥ 5 then
    set x to x - 1
    end if
    else if x = b then
    if x ≤ 1 then
    set x to x + 1
    end if
    if x ≥ 5 then
    set x to x - 1
    end if
    else
    set itemsOne to x & y & z & a & b
    end if
    set itemsOne to x & y & z & a & b
    itemsOne
    Any Ideas??
    Thanks for any help you can give,
    MrBlobE

    Hello
    In addition to what others have said.
    This sort of script could be done efficiently by class filtering of index list.
    The basic is this :
    {1, 2, false, 4, false}'s integers --> {1, 2, 4}
    {1, 2, false, 4, false}'s some integer --> {1, 2, 4}'s some item --> 2, e.g.
    Thus you might try something like this :
    --set nn to {1, 2, 3, 4, 5}
    set nn to "12345"
    return some_permutation(nn)
    on some_permutation(aa)
    script o
    property xx : aa -- source list
    property yy : {} -- result list
    property kk : {} -- index list
    repeat with k from 1 to count my xx
    set end of kk to k
    end repeat
    repeat (count my kk) times
    set k to my kk's some integer -- some integer (class filter)
    set my kk's item k to false -- suppress the chosen index
    set end of my yy to my xx's item k -- extract item by chosen index
    end repeat
    if my xx's class = list then
    return my yy's contents
    else
    return "" & my yy
    end if
    end script
    tell o to run
    end some_permutation
    Regards,
    H

  • How to genrate non-repeating random numbers

    Hi everyone, i'm trying to write a for loop that genrate a
    list of non-repeating random index number for an array list but i
    can't seem to get the random numbers non-repeat. I'm a newbie in
    Flex 2 so it would be great if anyone could show me what seems to
    be the problem in this code:
    Thank you very much.
    Richie
    for (var j:Number = 0; j < tempArray.length; j++)
    var randomNum:Number =
    Math.round(Math.random()*tempArray.length);
    if (j - 1 >= 0)
    while (randomNum == randomIndex[j-1].index)
    randomNum = Math.round(Math.random()*tempArray.length);
    //Push the random number in an array
    randomIndex.push({index: randomNum});
    Alert.show(randomNum.toString());
    }

    Dont' worry about it guys, i already got it thanks!

  • Stop random numbers repeating HELP!!

    i have been trying to create ten random numbers between 0-99 without them repeating and put them into an object array. this is the code i have been trying but it doesn't seem to work.
    public static void main (String[] args)
         Random generator = new Random();
         Object[] data = new Object[10];
         int marker = 0;
         for (int i = 0; i< data.length; i++)
         int number = Math.abs( generator.nextInt() )%99+1;
         Integer random = new Integer ( number );
         for ( int a = 0; a < data.length; a++ )
                   if ( ( data[a] ) == random )
                   marker = marker + 1;
                   if ( marker == 0 )
                        data[i] = random;
                   else
                        i = i - 1;
                        marker = 0;
              for (int i = 0; i < data.length; i++)
                   System.out.println( data[i] );

    redesign your code, how is that look? :)
    public static void main (String[] args)
      Random generator = new Random();
      Object[] data = new Object[10];
      Set set = HashSet();
      while(set.size() < 10)
        int number = Math.abs( generator.nextInt() )%99+1;
        Integer random = new Integer ( number );
        set.add(random);
      Iterator iter = set.iterator();
      int j = 0;
      while (iter.hasNext())
        data[j++] = iter.next();
      for (int i = 0; i < data.length; i++)
        System.out.println( data[i] );
    }--lichu                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Non repeating random numbers

    Hi,
    Im writing code to generate 10 random numbers and i have code written so that if a number between 1 and 10 is already chosen, it has to look for another number. heres snippets of the code:
    for (int b = 0; b < 2; b++)
    for (int i = 0; i < a.length; i++)
    int test = (int)(Math.random() * 10);
    boolean r = valueExists(test);
    if (r == (true))
    test = (int)(Math.random() * 10);
    else
    a[i] = test;
    boolean valueExists(int value)
    int z = a.length;
    boolean exists = false;
    for (int j = 0; j < z; j++)
    if (a[j] == value)
    exists = true;
    return exists;
    when i run this code, the numbers do repeat. can anyone help?

    import java.util.List;
    import java.util.ArrayList;
    import java.util.Random;
    public class RandomNumbersDemo {
        private List numbers = new ArrayList();
        private Random random = new Random();
        public static void main(String[] args) {
                 RandomNumbersDemo demo = new RandomNumbersDemo();
            demo.init();
            demo.doThatVoodoo();
        public void doThatVoodoo() {
            while (numbers.size() > 0) {
                System.out.println(getRandomInteger());
        public int getRandomInteger() {
            int element = random.nextInt(numbers.size());
            Integer randomInteger = (Integer) numbers.get(element);
            numbers.remove(element);
            return randomInteger.intValue();
        public void init() {
            for (int i = 0; i < 10; i++) {
                numbers.add(new Integer(i));

  • Working with random numbers

    is there a way of creating a series of 6 random numbers from 1-9 without repeating a single number? i have currently developed the following method which so far generates a random number excluding zero, but ive no idea of how to ensure that i get different numbers everytime....
    private int randomNumber ()     {
            int num;
            do {
                   num = (int) (Math.random()*10);
            } while (num == 0);
            return num;
    }anyone got any ideas?

    use this insteadRandom rand = new Random();
        // Random integers that range from from 0 to n
        int n = 10;
       int  i = rand.nextInt(n+1);

  • I am trying to generate an array of 30 random numbers. after every 5 readings a new vi should open and tell the user that 5 readings has been completed. and again carry on with the generation of array.

    since i do not have a transducer now, i am currently generating an array of 30 random numbers. after every 5 readings a warning should be given to the user that 5 readngs are complete. this cycle should repeat. the array size is 30.
    please help me out,  waiting for reply asap.
    once i have the transducer, i will be taking 30 analog samples and then after every 5 smaples that wraning will be displaye din a new VI
    Solved!
    Go to Solution.

    Use a while loop with a time delay representing your sampling period.
    Use the count terminal to check if equals 4, so 4th iteration=5th sample.
    Use a case structure. The true case will only be executed on the 4th iteration.
    In the true case place a subVI  with your desired message in the front panel. Go to the VI properties window and set "open front panel when called".
    The closing condition of the warnign is not giving in your description.
    Consider that rather than usign a subvi for this, you could use the "One/Two/Three button dialog" or "display message" vis at the "dialog and user interface" pallete.
    Please give it a try and send your own VI. Do not expect us to provide a working solution.
    Regards,

  • 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 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)

  • Random Numbers not playing fair!

    Hi All.
    Can anyone explain why I keep getting the same number out of the Random class? Each time I run my program, I get a different number, but it then repeats that same 'random' number. I've tried using the Math.random and that didn't seem to work either.
    Thanks
    Dr Nick

    This "repeating the same number" problem of Random is
    usually because it's instantiated many times in a
    loop. Random takes its seed from the system clock with
    a resolution of 1 millisecond. If random is
    instantiated many times during 1 millisecond it will
    use the same seed and thus deliver the same random
    numbers.That's all true, but he said he experienced this with java.lang.Math.random() which reuses the same random number generator. Here's the source for it:
        public static double random() {
            if (randomNumberGenerator == null) initRNG();
            return randomNumberGenerator.nextDouble();
        }"randomNumberGenerator" is static.

  • Randomize/shuffle array item without repeat actionscript 3.0

    i am creating a question and answer quiz using flash cs3 and actionscript 3.0.
    i have a large array of question, i wish to put it into xml document
    (can xml document be reside in the flash file itself?i thought ive seen someone did that.)
    ok,my main problem is to shuffle the questions without repeat until all questions were asked. i have worked on this tutorial,and it does great shuffling without repeat. http://www.flashandmath.com/howtos/deal/
    but,i wish to ask one question at once. i have looked into the option to shuffle frames, but i think about how can i count the score of the quiz at the end of it?
    can anyone tell me the best way of doing this?
    many thanks 

    . i have looked into the option to shuffle frames,
    you can`t really shuffle frames in flash, you have to tell the playhead of your movie to jumpp to a specific frame.
    so if you have say 20 Questions that are ordered in 20 kjeyframes along the main Timeline. you will have an array o Numbers from 1-20 that is shuffled by a function like you mentioned above.
    Then in the function that evaluates your answers that targets this aray as a pointer to where to go next.
    The pointer could be a simple Number, that describes the position of one specific number in this array, like so:
    //At the beginning of your quiz
    var randArray:Array = [1...20];
    var pointer:int = 0;
    var points:int = 0;
    var right:Boolean= false;
    //in the function that evaluates your answer
    function evaluateAnswer():void{
       if(right){
       points+=1;
    else{
    //don`t add Points
    //this will choose the next frame from your shuffled Array
    pointer++;
    if(pointer<=20){
    this.gotoAndPlay(randArray[pointer]);
    else{
    //when the last question is answered do something in a funtion that shows the result
    showResult();

Maybe you are looking for