์์ ๋ํ๊ธฐ
์ด๋ค ์ ์๋ค์ด ์์ต๋๋ค. ์ด ์ ์๋ค์ ์ ๋๊ฐ์ ์ฐจ๋ก๋๋ก ๋ด์ ์ ์ ๋ฐฐ์ด absolutes์ ์ด ์ ์๋ค์ ๋ถํธ๋ฅผ ์ฐจ๋ก๋๋ก ๋ด์ ๋ถ๋ฆฌ์ธ ๋ฐฐ์ด signs๊ฐ ๋งค๊ฐ๋ณ์๋ก ์ฃผ์ด์ง๋๋ค. ์ค์ ์ ์๋ค์ ํฉ์ ๊ตฌํ์ฌ return ํ๋๋ก solution ํจ์๋ฅผ ์์ฑํด์ฃผ์ธ์.
์ ํ ์กฐ๊ฑด
* absolutes์ ๊ธธ์ด๋ 1 ์ด์ 1,000 ์ดํ์
๋๋ค.
* absolutes์ ๋ชจ๋ ์๋ ๊ฐ๊ฐ 1 ์ด์ 1,000 ์ดํ์
๋๋ค.
* signs์ ๊ธธ์ด๋ absolutes์ ๊ธธ์ด์ ๊ฐ์ต๋๋ค.
* signs[i] ๊ฐ ์ฐธ์ด๋ฉด absolutes[i] ์ ์ค์ ์ ์๊ฐ ์์์์, ๊ทธ๋ ์ง ์์ผ๋ฉด ์์์์ ์๋ฏธํฉ๋๋ค.
์ ์ถ๋ ฅ ์
absolutes | signs | result |
---|---|---|
[4,7,12] | [true,false,true] | 9 |
[1,2,3] | [false,false,true] | 0 |
์
์ถ๋ ฅ ์ #1
* signs๊ฐ [true,false,true] ์ด๋ฏ๋ก, ์ค์ ์๋ค์ ๊ฐ์ ๊ฐ๊ฐ 4, -7, 12์
๋๋ค.
* ๋ฐ๋ผ์ ์ธ ์์ ํฉ์ธ 9๋ฅผ return ํด์ผ ํฉ๋๋ค.
์
์ถ๋ ฅ ์ #2
* signs๊ฐ [false,false,true] ์ด๋ฏ๋ก, ์ค์ ์๋ค์ ๊ฐ์ ๊ฐ๊ฐ -1, -2, 3์
๋๋ค.
* ๋ฐ๋ผ์ ์ธ ์์ ํฉ์ธ 0์ return ํด์ผ ํฉ๋๋ค.
๋ฌธ์ ํ์ด
forEach๋ฌธ์ผ๋ก true์ผ ๊ฒฝ์ฐ answer์ +=, ์๋ ๊ฒฝ์ฐ -=๋ก ํ๋ฌ์ค/๋ง์ด๋์ค๋ฅผ ๋ถ์ฌ ์์์ ๋ํด์ค๋๋ค. signs์์ true์ธ 4,12๋ ๊ทธ๋๋ก ๋ํ๊ณ false์ธ 7์ -7๋ก ์ ์ฅ๋ฉ๋๋ค. ๊ทธ๋์ ๋ต์ 9๊ฐ ๋ฉ๋๋ค. [1,2,3]์ ๊ฒฝ์ฐ [-1,-2,3]์ผ๋ก ๋ํ๋ฉด 0์ ๋๋ค.
function solution(absolutes, signs) {
let answer = 0;
absolutes.forEach((v, i) => {
if (signs[i]) {
answer += v;
} else {
answer -= v;
}
})
return answer;
}
๋ค๋ฅธ ํ์ด ๋ฐฉ์
reduce๋ก ํ ์ค๋ก ๊ฐ๋จํ ํธ๋ ๋ฐฉ๋ฒ์ด ์๋ค.
function solution(absolutes, signs) {
return absolutes.reduce((acc, val, i) => acc + (val * (signs[i] ? 1 : -1)), 0);
}
๋๊ธ