Non-repeating numbers

edited April 2018 in How To...

Hi! I want to fill an array with 10 random numbers (from 1 to 20) but I don't want them to repeat.. Could anyone help me with the simplest code possible? I tried to do this using for and if but it didn't worked.. :/

Answers

  • How would you do this in real life? Think lottery or bingo...

  • Make a list of 10, shuffle them and then pick the first/top 10.

    Check IntList in the reference.

    Kf

  • Fail. "From 1 to 20" it says.

  • edited April 2018
    // Forum.Processing.org/two/discussion/27692/non-repeating-numbers#Item_5
    // GoToLoop (2018-Apr-04)
    
    final IntList randomRangeList = IntList.fromRange(1, 21);
    
    randomRangeList.shuffle(this);
    randomRangeList.resize(10);
    println(randomRangeList);
    
    final int[] randomRangeArray = randomRangeList.array();
    println(randomRangeArray);
    
    exit();
    
  • edited April 2018
    // Forum.Processing.org/two/discussion/27692/non-repeating-numbers#Item_6
    // GoToLoop (2018-Apr-04)
    
    static final int QTY = 10, MIN_VAL = 1, MAX_VAL = 20 + 1;
    
    final IntList randomRangeList = IntList.fromRange(MIN_VAL, MAX_VAL);
    int[] randomRangeArray;
    
    int[] random10Range() {
      randomRangeList.shuffle(this);
      return expand(randomRangeList.values(), QTY);
    }
    
    void setup() {
      noLoop();
    }
    
    void draw() {
      background((color) random(#000000));
      randomRangeArray = random10Range();
    
      println();
      println(randomRangeArray);
    }
    
    void keyPressed() {
      redraw = true;
    }
    
    void mousePressed() {
      keyPressed();
    }
    
Sign In or Register to comment.