programing

Java를 사용하여 기본 요소 배열에서 max/min 값 찾기

prostudy 2022. 5. 27. 21:20
반응형

Java를 사용하여 기본 요소 배열에서 max/min 값 찾기

배열의 최소값/최대값을 결정하는 함수를 작성하는 것은 간단합니다.

/**
 * 
 * @param chars
 * @return the max value in the array of chars
 */
private static int maxValue(char[] chars) {
    int max = chars[0];
    for (int ktr = 0; ktr < chars.length; ktr++) {
        if (chars[ktr] > max) {
            max = chars[ktr];
        }
    }
    return max;
}

이건 이미 어디선가 한 거 아니에요?

Commons Lang 사용(변환) + 컬렉션 사용(최소/최대)

import java.util.Arrays;
import java.util.Collections;

import org.apache.commons.lang.ArrayUtils;

public class MinMaxValue {

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};

        List b = Arrays.asList(ArrayUtils.toObject(a));

        System.out.println(Collections.min(b));
        System.out.println(Collections.max(b));
   }
}

:Arrays.asList()는 기본 어레이를 랩하기 때문에 메모리를 너무 많이 사용하지 않아야 하며 어레이 요소에 대한 복사를 수행하지 않아야 합니다.

새로운 Java 8s는 간단하게 사용할 수 있지만,int.

유틸리티 클래스의 메서드는 메서드를 사용할 수 있는를 제공합니다., , , , ...도 할 수 있습니다.

이 메서드는 값 취득에 사용됩니다.

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)
    }

}

==UPDATE==

실행 시간이 중요한 경우 이러한 방법을 사용할 수 있는 경우에만 데이터를 검토해야 합니다.

import java.util.Arrays;
import java.util.IntSummaryStatistics;

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

이 방법은 환원 연산이며 병렬화가 가능하기 때문에 기존 루프보다 더 나은 성능을 제공할 수 있습니다.

Google Guava 라이브러리는 Chars, Ints, Longs 등의 클래스에 최소 메서드와 최대 메서드가 있습니다.

다음과 같이 간단하게 사용할 수 있습니다.

Chars.min(myarray)

변환은 불필요하며, 아마 효율적으로 구현될 것입니다.

배열을 정렬하면 min/max의 처음과 마지막 값을 얻을 수 있습니다.

import java.util.Arrays;

public class apples {

  public static void main(String[] args) {
    int a[] = {2,5,3,7,8};
    Arrays.sort(a);

    int min =a[0];
    System.out.println(min);

    int max= a[a.length-1];
    System.out.println(max);
  }
    
}

단순한 루프로 최소/최대값을 찾는 것보다 정렬 작업이 더 비싸지만,다만, 퍼포먼스가 문제가 되지 않는 경우(예를 들면, 스몰 어레이, 또는 사용의 애플리케이션에 코스트가 관계없는 경우)에는, 매우 심플한 솔루션입니다.

주의: 이 후 어레이도 변경됩니다.

네, 컬렉션 클래스에서 합니다.기본 문자 배열은 수동으로 문자[]로 변환해야 합니다.

간단한 데모:

import java.util.*;

public class Main {

    public static Character[] convert(char[] chars) {
        Character[] copy = new Character[chars.length];
        for(int i = 0; i < copy.length; i++) {
            copy[i] = Character.valueOf(chars[i]);
        }
        return copy;
    }

    public static void main(String[] args) {
        char[] a = {'3', '5', '1', '4', '2'};
        Character[] b = convert(a);
        System.out.println(Collections.max(Arrays.asList(b)));
    }
}

모든 응용 프로그램에 다음과 같은 방법으로 도우미 클래스가 있습니다.

public static double arrayMax(double[] arr) {
    double max = Double.NEGATIVE_INFINITY;

    for(double cur: arr)
        max = Math.max(max, cur);

    return max;
}

하면 할 수요.IntStreammax()★★★★★★ 。

public static int maxValue(final int[] intArray) {
  return IntStream.range(0, intArray.length).map(i -> intArray[i]).max().getAsInt();
}

설명.

  1. range(0, intArray.length)- 에 - 에 있는 스트림을 얻어야 합니다.intArray.

  2. map(i -> intArray[i])- 를 - 스트림의 intArray.

  3. max()이를 다음과 같이 . - 이 스트림의 최대 요소:OptionalInt.

  4. getAsInt()을 풀어주세요 - 개봉하다OptionalInt (할 수 .)orElse(0)을 위해OptionalInt는 비어 있습니다).

    public int getMin(int[] values){
        int ret = values[0];
        for(int i = 1; i < values.length; i++)
            ret = Math.min(ret,values[i]);
        return ret;
    }
import java.util.Random;

public class Main {

public static void main(String[] args) {
   int a[] = new int [100];
   Random rnd = new Random ();

    for (int i = 0; i< a.length; i++) {
        a[i] = rnd.nextInt(99-0)+0;
        System.out.println(a[i]);
    }

    int max = 0;          

    for (int i = 0; i < a.length; i++) {
        a[i] = max;


        for (int j = i+1; j<a.length; j++) {
            if (a[j] > max) {
               max = a[j];
            }

        }
    }

    System.out.println("Max element: " + max);
}
}

솔루션:reduce():

int[] array = {23, 3, 56, 97, 42};
// directly print out
Arrays.stream(array).reduce((x, y) -> x > y ? x : y).ifPresent(System.out::println);

// get the result as an int
int res = Arrays.stream(array).reduce((x, y) -> x > y ? x : y).getAsInt();
System.out.println(res);
>>
97
97

위의 코드에서는reduce()데이터를 반환하다Optional변환 가능한 형식int타고getAsInt().

최대값을 특정 수치와 비교하려면 다음 중 시작값을 설정할 수 있습니다.reduce():

int[] array = {23, 3, 56, 97, 42};
// e.g., compare with 100
int max = Arrays.stream(array).reduce(100, (x, y) -> x > y ? x : y);
System.out.println(max);
>>
100

위의 코드에서는,reduce()identity(시작값)를 첫 번째 파라미터로 지정하면 ID와 같은 형식의 데이터가 반환됩니다.이 속성을 사용하여 이 솔루션을 다른 어레이에 적용할 수 있습니다.

double[] array = {23.1, 3, 56.6, 97, 42};
double max = Arrays.stream(array).reduce(array[0], (x, y) -> x > y ? x : y);
System.out.println(max);
>>
97.0

여기 유틸리티 클래스가 있습니다.min/max프리미티브 유형의 메서드: Primitives.java

int [] numbers= {10,1,8,7,6,5,2};
    int a=Integer.MAX_VALUE;
    for(int c:numbers) {
        a=c<a?c:a;
        }
        
    System.out.println("Lowest value is"+a);

플로트를 사용한 예:

public static float getMaxFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[data.length - 1];
}

public static float getMinFloat(float[] data) {

    float[] copy = Arrays.copyOf(data, data.length);
    Arrays.sort(copy);
    return copy[0];
}

어레이를 정렬하는 메서드에 전달합니다.Arrays.sort()따라서 메서드가 사용하는 배열만 정렬하고 min을array[0]최대값array[array.length-1].

저지

public class MinMaxValueOfArray {
    public static void main(String[] args) {
        int[] A = {2, 4, 3, 5, 5};
        Arrays.sort(A);
        int min = A[0];
        int max = A[A.length -1];
        System.out.println("Min Value = " + min);        
        System.out.println("Max Value = " + max);
    }
}

다음은 실행의 약 99%에서 최대값을 얻을 수 있는 솔루션입니다(더 나은 결과를 얻으려면 0.01을 변경하십시오).

public static double getMax(double[] vals){
    final double[] max = {Double.NEGATIVE_INFINITY};

    IntStream.of(new Random().ints((int) Math.ceil(Math.log(0.01) / Math.log(1.0 - (1.0/vals.length))),0,vals.length).toArray())
            .forEach(r -> max[0] = (max[0] < vals[r])? vals[r]: max[0]);

    return max[0];
}

(전혀 심각하지 않음)

    int[] arr = {1, 2, 3};

    List<Integer> list = Arrays.stream(arr).boxed().collect(Collectors.toList());
    int max_ = Collections.max(list);
    int i;
    if (max_ > 0) {
        for (i = 1; i < Collections.max(list); i++) {
            if (!list.contains(i)) {
                System.out.println(i);
                break;
            }
        }
        if(i==max_){
            System.out.println(i+1);
        }
    } else {
        System.out.println("1");
    }
}

언급URL : https://stackoverflow.com/questions/1484347/finding-the-max-min-value-in-an-array-of-primitives-using-java

반응형