코딩테스트/프로그래머스

[프로그래머스] Lv.0 등차수열의 특정한 항만 더하기(Java)

선SEON 2023. 10. 25. 18:50

1. 문제

 

2. 제출 답안

class Solution {
    public int solution(int a, int d, boolean[] included) {
        int n = included.length; // n은 included의 배열의 길이, 배열의 길이 = 등차수열의 길이
        int answer = 0; // 합 변수 초기화

        for(int i = 0; i < n; i++){ // 반복문으로 included 배열 순회
            if(included[i]){ // 현재 항이 true인 경우만 처리
                answer += a + i * d; // 선택된 항의 값 계산 후 더하기
            }
        }
        return answer;
    }
}

 

3. 다른 풀이

import java.util.stream.IntStream;

class Solution {
    public int solution(int a, int d, boolean[] included) {
        return IntStream.range(0, included.length).map(idx -> included[idx]?a+(idx*d):0).sum();
    }
}

Stream(스트림)을 사용할 생각은 못했네..!

1. IntStream.range(0, included.length)은 included 배열의 길이에 맞는 정수 스트림을 생성.
   이 스트림은 0부터 included.length - 1까지의 정수를 포함.

2. map 메서드를 사용하여 각 인덱스(idx)에 대한 계산을 수행.
    included[idx]가 true인 경우, a + (idx * d)를 반환하고, 그렇지 않으면 0을 반환.

3. sum 메서드를 사용하여 스트림의 모든 요소를 합산.
   이렇게 계산된 값은 등차수열에서 included 배열이 true인 항들의 합이 됨.

4. 계산된 합을 반환