boj - 1940 주몽(자바)

SlowAnd·2024년 1월 1일
0

https://www.acmicpc.net/problem/1940

1. 하드코딩 2중 for문

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter w = new BufferedWriter(new OutputStreamWriter(System.out));
        r.readLine();
        int sum = Integer.parseInt(r.readLine());
        int count =0;
        List<Integer> collect = Arrays.stream(r.readLine().split(" ")).mapToInt(Integer::parseInt).boxed()
                .collect(Collectors.toList());
        int size = collect.size();
        for(int i=0; i< size-1; i++){
            for(int j= i+1; j<size; j++) {
                int count1 = collect.get(i) + collect.get(j);
                if( count1== sum){
                    count++;
                }
            }
        }
        w.write(count+"");w.flush();
        
    }
}

2. 람다스트림 2중 for문

public class Main {
    public static void main(String[] args) throws IOException {

        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(r.readLine()); // 재료의 개수
        int M = Integer.parseInt(r.readLine()); // 갑옷을 만드는 데 필요한 수
        List<Integer> materials = Arrays.stream(r.readLine().split(" "))
                .map(Integer::parseInt)
                .collect(Collectors.toList());

        int count = (int) IntStream.range(0, N)
                .flatMap(i -> IntStream.range(i + 1, N)
                        .map(j -> materials.get(i) + materials.get(j)))
                .filter(sum -> sum == M)
                .count();

        System.out.println(count);

    }
}

3. 깔끔 람다 스트림

public class s {
    public static void main(String[] args) throws IOException {
        BufferedReader r = new BufferedReader(new InputStreamReader(System.in));

        int N = Integer.parseInt(r.readLine()); // 재료의 개수
        int M = Integer.parseInt(r.readLine()); // 갑옷을 만드는 데 필요한 수
        List<Integer> materials = Arrays.stream(r.readLine().split(" "))
                                        .map(Integer::parseInt)
                                        .collect(Collectors.toList());

        int count = IntStream.range(0, N)
            .flatMap(i -> IntStream.range(i + 1, N)
                .map(j -> materials.get(i) + materials.get(j) == M ? 1 : 0))
            .reduce(0, Integer::sum);

        System.out.println(count);
    }
}

0개의 댓글