Generating random array of fixed length (Java)

前端 未结 3 1526
南方客
南方客 2021-01-27 00:07

im just looking to change my code so that a random array of a fixed length of 100 integers is generated every time the code is ran rather than just have a pre-set array within t

相关标签:
3条回答
  • 2021-01-27 00:45

    The below would fill an array of 100 integers with Random numbers from 1-1000

    int[] numbers= new int[100];
    Random rand = new Random();
    for (int i = 0; i < numbers.length; i++) {
          numbers[i] = rand.nextInt(1000);
    }
    

    However note that the above code might insert duplicates. If you want to avoid that, using a List in parallel to the array and checking whether the generated value already exists should ensure uniqueness :

    int[] numbers= new int[100];
    List<Integer> numbersList = new ArrayList<Integer>(numbers.length);
    Random rand = new Random();
    for (int i = 0; i < numbers.length; i++) {
        int j = rand.nextInt(1000);
        while (numbersList.contains(j)) {
            j = rand.nextInt(1000);
        }
        numbers[i] = j;
        numbersList.add(j);
    }
    

    Even though I think it would be wiser to get rid of the array and use just the List...

    0 讨论(0)
  • 2021-01-27 01:02

    You should look at the Random class. More specifically:

    1. nextInt() to fill it one by one
    2. ints​(long) to get an IntStream of fixed size, which can be easily converted to an array with .toArray()
    0 讨论(0)
  • 2021-01-27 01:04
    public class Selectionsort { 
         public static void main(String[] args) {     
            int[]numbers= new int[100]
            Random random = new Random();
    
           for(int i=0;i<numbers.length;i++){
               numbers[i]=random.nextInt(100);
           }
           sort(numbers); 
    
           printArray(numbers);
      } 
    

    The above snippet will help you to create a random numbers between 1 to 100 for the array of size 100.

    0 讨论(0)
提交回复
热议问题