0

I would like all the number up to an upperbound to be chosen randomly with each number from 1 to upper bound only appearing once. For example if i have the number 5. I would like all the numbers from 1 to 5 be printed to an array but randomly, such as [5,2,3,1,4].

I would do this with a double for loop and check if my random number generator gives a number that is already chosen, if not I would store the value into the array. This seems like a really inefficient method, is there a better way to do this?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Tony
  • 387
  • 1
  • 2
  • 14

3 Answers3

2

Try this:

List<Integer> list = IntStream.rangeClosed(1, upperBound)
                              .boxed().collect(toList());
Collections.shuffle(list);
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

One way to solve this would be to generate an array containing 1 through N, then shuffle it; see @Bohemian's answer for a concise way to express this ... though his code is producing a List<Integer> rather than an int[].

However, unless you can predict that N is liable to be large (or this procedure is going to be done many, many times) the (assumed) inefficiency of your solution should not be a concern. Resist the temptation of premature optimization ...

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

I think while loop can help you with it and use contains to check if the number is in the list.

 public class Main
    {
        public static void main(String[] args) {
            // set the upper bound
            int upperBound = 5;
            
            // create an ArrayList to store the numbers
            List<Integer> numList = new ArrayList<Integer>(upperBound-1);
            
            // use random object to generate random number
            Random rand = new Random();
            
            // use a while loop to generate random number
            while(numList.size() <= upperBound){
                int i = rand.nextInt(upperBound+1);
                if(!numList.contains(i)&&i!=0){
                    numList.add(i);
                }
            }
            
            // print the value
            for(int num:numList){
                System.out.println(num);
            }
            
        }
    }
user14761376
  • 691
  • 1
  • 4
  • 3