G
G
Gleb Zubov2019-03-04 22:48:46
Java
Gleb Zubov, 2019-03-04 22:48:46

How to find min and max?

Hello!
In general, I encountered such a problem, we were asked to make an algorithm for finding the location of mines and max in an array.
Here's what I've done so far (but even it doesn't work properly)

public static void main(String[] args) {
        ArrayList<Integer> wyrazy= new ArrayList<>();
        Random generator = new Random(); 
        int i = 0;
        int n_n=100;
        int n = 10;
        int b = 0;
        while(i!=n)
        {
        int random=generator.nextInt(n_n);
        wyrazy.add(random);
        i++;
        }
        System.out.println(wyrazy);
        int t = 0;
        int min = wyrazy.get(t);
        System.out.println(min);
        while(t<wyrazy.size()-1)
        {
        t++;
        while(wyrazy.get(t)<min)
        {min = wyrazy.get(t);
        b++;
        }
        }
        System.out.println(b);
        System.out.println(min);
        System.out.println(wyrazy.get(t));
    }

I found this site: http://school-collection.lyceum62.ru/ecor/storage/...
Here I found the algorithms for finding Max and Min (But for Paskal)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maksim Ivanov, 2019-03-04
@Povedli

import java.util.Arrays;

public class Test {
    public static void main(String[] args){
        int[] tab = {12, 1, 21, 8};
        int min = Arrays.stream(tab).min().getAsInt();
        int max = Arrays.stream(tab).max().getAsInt();
        System.out.println("Min = " + min);
        System.out.println("Max = " + max)
    }

}

You can just use the new Java 8 Stream s, but you need to work with int.
The Stream class method of Arrays gives you an IntStream on which you can use min. You can also do max, sum, average,...
The getAsInt method is used to get the value from the OptionalInt

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question