jeudi 8 avril 2021

searching for the highest and the smallest value in a specific range - Random

Hello, so far in the program the values were searched randomly, but I want to modify the program to search for random numbers in a given range. Generally speaking My point is that the draw should be from the given range (from - to), and not up to 1000 random numbers as in the above code, so my question is:

How can I pass the value from and to to random: rand.nextInt (?) so that the numbers are randomly drawn in a given range. so I generally need to get a printout from the program like in the question: expected output

// Create array to be searched
final int[] arrayToSearch = new int[20];
        Random rnd = new Random();
        for (int i = 0; i < arrayToSearch.length; i++)
        arrayToSearch[i] = rnd.nextInt(1000);
        System.out.println(Arrays.toString(arrayToSearch));

final int PARTITIONS = 4;
        Thread[] threads = new Thread[PARTITIONS];
final int[] partitionMin = new int[PARTITIONS];
final int[] partitionMax = new int[PARTITIONS];
        for (int i = 0; i < PARTITIONS; i++) {
final int partition = i;
        threads[i] = new Thread(new Runnable() {
@Override
public void run() {
        // Find min/max values in sub-array
        int from = arrayToSearch.length * partition / PARTITIONS;
        int to = arrayToSearch.length * (partition + 1) / PARTITIONS;
        int min = Integer.MAX_VALUE,
        max = Integer.MIN_VALUE;
        for (int j = from; j < to; j++) {
        min = Math.min(min, arrayToSearch[j]);
        max = Math.max(max, arrayToSearch[j]);
        }
        partitionMin[partition] = min;
        partitionMax[partition] = max;

        });

so far:

partition 0: from=0, to=5, min=23, max=662 //the draw in the range 0-5, draw is outside the specified range

expected output:

partition 1: from=0, to=5, min=1, max=3 // the draw takes place within the given range 0 to 5
partition 2: from=20, to=30, min=22, max=29 //the draw takes place within the given range 20 to 30



Aucun commentaire:

Enregistrer un commentaire