๐Ÿ–ค Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ์ถ”์–ต ์ ์ˆ˜ (Javascript)

์˜ˆ์ง„-D 2023. 5. 9. 15:17

https://school.programmers.co.kr/learn/challenges?order=recent&statuses=unsolved&levels=1&languages=javascript 

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต | ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์Šค์ฟจ

๊ฐœ๋ฐœ์ž ์ทจ์—…์˜ ํ•„์ˆ˜ ๊ด€๋ฌธ ์ฝ”๋”ฉํ…Œ์ŠคํŠธ๋ฅผ ์ฒ ์ €ํ•˜๊ฒŒ ์—ฐ์Šตํ•˜๊ณ  ๋Œ€๋น„ํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ๋ฅผ ์ด๋ง๋ผ! ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์—์„œ ์„ ๋ฐœํ•œ ๋ฌธ์ œ๋กœ ์œ ํ˜•์„ ํŒŒ์•…ํ•˜๊ณ  ์‹ค๋ ฅ์„ ์—…๊ทธ๋ ˆ์ด๋“œํ•ด ๋ณด์„ธ์š”!

school.programmers.co.kr

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต์—์„œ ํ™•์ธํ•  ์ˆ˜ ์žˆ๋Š” ์ถ”์–ต ์ ์ˆ˜ ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค. ์ง€๋‚œ ๋‹ฌ๋ฆฌ๊ธฐ ๊ฒฝ์ฃผ์—์„œ ์ƒˆ๋กœ ๋ฐฐ์šด hash๋ฅผ ๋‹ค์‹œ ์‚ฌ์šฉํ•˜์—ฌ ํฌ์ŠคํŒ…ํ•ฉ๋‹ˆ๋‹ค!

 

 

 

๋ฌธ์ œ

์‚ฌ์ง„๋“ค์„ ๋ณด๋ฉฐ ์ถ”์–ต์— ์ –์–ด ์žˆ๋˜ ๋ฃจ๋Š” ์‚ฌ์ง„๋ณ„๋กœ ์ถ”์–ต ์ ์ˆ˜๋ฅผ ๋งค๊ธธ๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค. ์‚ฌ์ง„ ์†์— ๋‚˜์˜ค๋Š” ์ธ๋ฌผ์˜ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๋ฅผ ๋ชจ๋‘ ํ•ฉ์‚ฐํ•œ ๊ฐ’์ด ํ•ด๋‹น ์‚ฌ์ง„์˜ ์ถ”์–ต ์ ์ˆ˜๊ฐ€ ๋ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด ์‚ฌ์ง„ ์† ์ธ๋ฌผ์˜ ์ด๋ฆ„์ด ["may", "kein", "kain"]์ด๊ณ  ๊ฐ ์ธ๋ฌผ์˜ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๊ฐ€ [5์ , 10์ , 1์ ]์ผ ๋•Œ ํ•ด๋‹น ์‚ฌ์ง„์˜ ์ถ”์–ต ์ ์ˆ˜๋Š” 16(5 + 10 + 1)์ ์ด ๋ฉ๋‹ˆ๋‹ค. ๋‹ค๋ฅธ ์‚ฌ์ง„ ์† ์ธ๋ฌผ์˜ ์ด๋ฆ„์ด ["kali", "mari", "don", "tony"]์ด๊ณ  ["kali", "mari", "don"]์˜ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๊ฐ€ ๊ฐ๊ฐ [11์ , 1์ , 55์ ]]์ด๊ณ , "tony"๋Š” ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๊ฐ€ ์—†์„ ๋•Œ, ์ด ์‚ฌ์ง„์˜ ์ถ”์–ต ์ ์ˆ˜๋Š” 3๋ช…์˜ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๋ฅผ ํ•ฉํ•œ 67(11 + 1 + 55)์ ์ž…๋‹ˆ๋‹ค.

๊ทธ๋ฆฌ์›Œํ•˜๋Š” ์‚ฌ๋žŒ์˜ ์ด๋ฆ„์„ ๋‹ด์€ ๋ฌธ์ž์—ด ๋ฐฐ์—ด name, ๊ฐ ์‚ฌ๋žŒ๋ณ„ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๋ฅผ ๋‹ด์€ ์ •์ˆ˜ ๋ฐฐ์—ด yearning, ๊ฐ ์‚ฌ์ง„์— ์ฐํžŒ ์ธ๋ฌผ์˜ ์ด๋ฆ„์„ ๋‹ด์€ ์ด์ฐจ์› ๋ฌธ์ž์—ด ๋ฐฐ์—ด photo๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ, ์‚ฌ์ง„๋“ค์˜ ์ถ”์–ต ์ ์ˆ˜๋ฅผ photo์— ์ฃผ์–ด์ง„ ์ˆœ์„œ๋Œ€๋กœ ๋ฐฐ์—ด์— ๋‹ด์•„ returnํ•˜๋Š” solution ํ•จ์ˆ˜๋ฅผ ์™„์„ฑํ•ด์ฃผ์„ธ์š”.

 

 

 

ํ’€์ด

์ด๋ฆ„์ด ๋‹ด๊ธด name๊ณผ ๊ทธ๋ฆฌ์›€ ์ ์ˆ˜๋ฅผ ๋‹ด์€ yearning์„ ํ•ฉ์ณ ํŽธํ•˜๊ฒŒ ์ธ๋ฑ์‹ฑ ํ•˜๊ธฐ ์œ„ํ•˜์—ฌ Map์— set ํ•ด์ค๋‹ˆ๋‹ค. ์ดํ›„ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด get ํ•ด์˜ค๋Š” ๋ฐฉ์‹์œผ๋กœ ์ฝ”๋“œ๋ฅผ ์ž‘์„ฑํ–ˆ๋Š”๋ฐ, ์ด๋ฒˆ ๋ฌธ์ œ๋Š” ํ†ต๊ณผํ–ˆ์ง€๋งŒ ์‹œ๊ฐ„ ๋ณต์žก๋„๋ฅผ ๋” ๋‚ฎ์ถœ ๋ฐฉ๋ฒ•์€ ์—†๋Š”์ง€ ๊ณ ๋ฏผํ•ด์•ผ๊ฒ ์Šต๋‹ˆ๋‹ค..

function solution(name, yearning, photo) {
    var answer = [];
    
    const hash = new Map();
    
    name.forEach((val, i) => {
        hash.set(val, yearning[i]);
    });
    
    for (val of photo) {
        let sum = 0;
        for (ele of val) {
            const temp = hash.get(ele);
            if (temp) {
                sum += temp;
            }
        }
        answer.push(sum)
    }
    return answer;
}