본문 바로가기

코딩/코테

두 배열을 곱하여 최솟값 구하기

두배열의 동일한 인덱스 요소들간의 곱의 합계 계산하는 함수가 있을 때
함수의 최소값을 출력하기 위해 첫번째 배열만 정렬 가능할 때 (두번째 배열 재배열 불가)
입력된 두 배열에 대한 함수의 최솟값을 출력
함수S = A[0]B[0] + … + A[N-1]B[N-1]

 

package me.gd.restapi.gdrestapi;

import org.springframework.boot.test.context.SpringBootTest;
import java.util.*;

@SpringBootTest
public class TEst {

    public static void main(String[] args) {

        List<Integer> a = Arrays.asList(1,5,3,2,4);
        List<Integer> b = Arrays.asList(12,9,8,7,11);

        // b를 정렬하면서 각 인덱스가 몇번째 순위인지 알아야 함


        Integer[] data = { 12, 9, 8, 7, 11 };
        Integer[] idx = new Integer[data.length]; // [3, 2, 1, 4, 0]

        for(int i=0; i<data.length; i++) {
            idx[i] = i;
        }

        Arrays.sort(idx, new Comparator<Integer>() {
            @Override public int compare(final Integer o1, final Integer o2) {
                return Integer.compare( data[o2], data[o1]);
            }
        });

        // a를 정렬해서 순서대로 곱하기
        Collections.sort(a);

        // 곱하기 담을 배열
        List<Integer> multiplyAandB = new ArrayList<>();

        for(int i =0; i < a.size(); i++) {
            int j = idx[i];
            int q = a.get(i);
            int w = b.get(j);

            System.out.println("a 입력값 중 최소값 : " + q);
            System.out.println("b 입력값 중 최대값 : " + w);
            System.out.println();

            multiplyAandB.add(q*w);
        }

        System.out.println("답 : " + sum(multiplyAandB));


    }

    public static int sum(List<Integer> list) {
        int sum = 0;
        for (int i: list) {
            sum += i;
        }
        return sum;
    }

}

 

stackoverflow.com/questions/951848/java-array-sort-quick-way-to-get-a-sorted-list-of-indices-of-an-array/35701049

 

Java Array sort: Quick way to get a sorted list of indices of an array

The problem: Consider the following floats[]: d[i] = 1.7 -0.3 2.1 0.5 What I want is an array of int[] that represents the order of the original array with indices. s[i] = 1 3 ...

stackoverflow.com

배열을 재배열 하지않고 새로운 리스트에 순위만 인덱스로 따면 끝

'코딩 > 코테' 카테고리의 다른 글

리스트에서 중복된 element끼리 그룹짓기  (0) 2020.11.20