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
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...
You should look at the Random class. More specifically:
nextInt()
to fill it one by oneints(long)
to get an IntStream of fixed size, which can be easily converted to an array with .toArray()
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.