[프로그래머스] Level1- 음양 더하기

JIEUN YANG·2023년 1월 20일
0

What i have to do in this problem is to add all the numbers based on each integer's sign.
Signs array has Boolean type as each element. 'true' element represents a positive element, but 'false' means a negative one.
Step by step, i thought of changing each element of absolutes to interger according to a real sign and add all numbers using 'reduce' method.


First, change absolutes's element to a real interger using 'map' method.

And then, return sum added all elements using 'reduce'


My Code.


function solution(ab, signs) {
    const real = ab.map((num, idx)=> {
        return signs[idx] === false ? -num : +num
    })
    
    return real.reduce((acc,cur)=> acc+cur, 0)
}

This can be passed in all cases. But, wanted to make them shorter and more effective, I searched a best code and noticed that 'reduce' method can be used a lot.



A simplest Code.

function solution(absolutes, signs) {
    return absolutes.reduce((acc, val, i) => acc + (val * (signs[i] ? 1 : -1)), 0);
}

Surprisingly, multiply 1 or -1 by curent element was the key point to solve this problem. It didn't need to change each to a real sign, If being dealt with addition to multiplied sign by current value. What a amazing !

profile
violet's development note

0개의 댓글