๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

ํ”„์—” ๊ณต๋ถ€/๐Ÿซง ์•Œ๊ณ ๋ฆฌ์ฆ˜ ๊ณต๋ถ€

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] [1์ฐจ] ๋‹คํŠธ ๊ฒŒ์ž„

728x90

๋‹น์—ฐํ•œ ์–˜๊ธฐ์ง€๋งŒ, ๋ฌธ์ œ๋ฅผ ์ž˜ ์ฝ๊ณ  ํŒจํ„ด์„ ๋นจ๋ฆฌ ํŒŒ์•…ํ•ด์•ผ ๋ฌธ์ œ๋ฅผ ๋นจ๋ฆฌ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค....

(ํŠนํžˆ ์กฐ๊ฑด๋“ค์ด ๋ณต์žกํ•  ๋•,,)

 

function solution(dartResult) {
    const score = dartResult.split(/[^0-9]/).filter(v => v !== "")
    const result = dartResult.split(/[0-9]/).filter(v => v !== "");
    let sumAll = [];
    result.map((v, i) => {
        let sum = v[0] == "S" ? score[i] : v[0] == "D" ? score[i] ** 2 : score[i] ** 3;
        if (!v[1]) {
            sumAll.push(Number(sum));
        }
        if (v[1] == "#") {
            sum = sum * -1;
            sumAll.push(Number(sum));
        }
        if (v[1] == "*") {
            if (i === 0) {
                sum *= 2;
                sumAll.push(Number(sum));
            } else {
                sumAll[i - 1] *= 2;
                sumAll.push(sum * 2)
            }
        }
    })
    return sumAll.reduce((a, b) => a + b);
}

 

์ •๊ทœ์‹์œผ๋กœ ๊ฐ ํšŒ์ฐจ๋ฅผ ์ชผ๊ฐœ์ค€๋‹ค.

[ '1', '2', '3' ] [ 'S', 'D*', 'T' ]

๊ทธ๋Ÿผ score, result ๊ฐ€ ์ด๋Ÿฐ ์‹์œผ๋กœ ๋‚˜์˜ด. 

result arr ๋ฅผ map ์œผ๋กœ ๋Œ๋ฆฌ๋ฉฐ, ๋จผ์ € ์•ŒํŒŒ๋ฒณ์— ๋”ฐ๋ฅธ ์ ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด์ค€๋‹ค.

๊ทธ๋ฆฌ๊ณ  ๋‹ค์Œ ๊ธ€์ž์ธ v[1] ์„ ๊ธฐ์ค€์œผ๋กœ 2๋ฅผ ๊ณฑํ•˜๊ฑฐ๋‚˜ -1๋ฅผ ๊ณฑํ•ด์ค€๋‹ค. 

๊ฐ€๊ณต์ด ๋‹ค ๋œ ์ ์ˆ˜๋Š” scoreAll ์— ๋„ฃ์–ด์ค€๋‹ค.

 

์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•ด์•ผํ•  ์ ์€ * ๊ฐ€ ์ด์ „์— ๋‚˜์™”๋˜ ๊ฒฝ์šฐ ์ด์ „ ์ ์ˆ˜๊นŒ์ง€ ๋ณ€๊ฒฝ๋œ๋‹ค๋Š” ์ ์ด๋‹ค.

 

3๋ผ์šด๋“œ๊นŒ์ง€์˜ ์ ์ˆ˜๋ฅผ push ํ•ด์ค€ ๋’ค, reduce ๋ฅผ ์ด์šฉํ•ด์„œ ํ•ฉ์นœ ์ ์ˆ˜๋ฅผ return ํ•ด์ค€๋‹ค. 

 

์ค‘๋ณต๋˜๋Š” ์ฝ”๋“œ๊ฐ€ ๋งŽ์•„๋ณด์—ฌ์„œ ๊ณ ์ณ๋ณด๋ ค๊ณ  ํ–ˆ๋Š”๋ฐ ํ  ์ž˜ ์•ˆ๋œ๋‹ค...

์˜ค๋Š˜๋„ ํ’€์–ด๋ƒˆ์Œ์— ์˜์˜๋ฅผ..!

 

728x90
๋ฐ˜์‘ํ˜•