코딩테스트
프로그래머스 | 음양 더하기
다시은
2023. 12. 26. 10:07

class Solution {
fun solution(absolutes: IntArray, signs: BooleanArray): Int {
var answer: Int = 0
for((i,s) in signs.withIndex()){
for((ii, a) in absolutes.withIndex()) {
if(s == true && i == ii) {
answer += a
} else if ( s == false && i == ii ){
answer -= a
}
}
}
return answer
}
}
각각의 배열의 인덱스가 일치하는 경우 값을 더하거나 빼서 구했다.
줄이고 싶은데 방법을 모르겠다 🤨
다른 사람 풀이
class Solution {
fun solution(absolutes: IntArray, signs: BooleanArray) =
absolutes.foldIndexed(0) { idx, acc, num -> acc + if (signs[idx]) num else -num }
} ^누적 ^원소
저번에 봤던 fold 함수를 index와도 쓸 수 있구나
fold 메소드 참조
https://www.codevscolor.com/kotlin-fold-foldindexed-foldright-foldrightindexed