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

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

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ๋ฌธ์ž์—ด์ด ๋ช‡ ๋ฒˆ ๋“ฑ์žฅํ•˜๋Š”์ง€ ์„ธ๊ธฐ - reduce ํ™œ์šฉ๋ฒ•

728x90

์ด ๋ฌธ์ œ๋Š” ํ’€์—ˆ๋‹ค๊ธฐ ๋ณด๋‹จ ๋‹ค๋ฅธ ์‚ฌ๋žŒ ์ฝ”๋“œ๋ฅผ ๋ณด๊ณ  ๊ณต๋ถ€ํ–ˆ๋‹ค..!

 

 

reduce ๋ฅผ ์ด์šฉํ•ด ์„ธ์•ผํ•˜๋Š” ๊ฐ’๋งŒ count ํ•ด์ค€๋‹ค. 

์„ธ์•ผ ํ•˜๋Š” ๊ฐ’์€ conStr ๊ณผ pat ์„ ๋น„๊ตํ•˜๋ฉด ๋œ๋‹ค.

๋น„๊ตํ•  conStr ์€ ๊ธฐ์กด ๋ฌธ์ž๋ฅผ pat ์˜ ๊ธธ์ด๋งŒํผ์”ฉ ์ž˜๋ผ๋‚ธ ๊ฐ’์ธ๋ฐ, 

์„ค๋ช…์ฒ˜๋Ÿผ ์ƒˆ๋กœ์šด ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ๊ธฐ์กด์— ์ฃผ์–ด์ง„ myString ์—๋Š” ์˜ํ–ฅ์„ ๋ฏธ์น˜์ง€ ์•Š๋Š”๋‹ค.

 

function solution(myString, pat) {
    const result = [...myString].reduce((acc, cur, ind) => {
        const conStr = myString.slice(ind, pat.length + ind)
        console.log(acc, cur, ind)
        return conStr === pat ? acc + 1 : acc;
    }, 0);
    console.log("result", result)
}
"banana", "ana" ์ธ ๊ฒฝ์šฐ ์ถœ๋ ฅ๊ฐ’

0 b 0
0 a 1
1 n 2
1 a 3
2 n 4
2 a 5
result 2

๋น„๊ตํ•ด์„œ ๊ฐ™์€ ๋ฌธ์ž์ผ ๊ฒฝ์šฐ์—๋งŒ acc ๊ฐ’์— +1์„ ํ•ด์ฃผ๊ธฐ ๋•Œ๋ฌธ์— 

๋‚˜์ค‘์— return ๋˜๋Š” ๊ฐ’์ด ๊ฐ™์€ ๋ฌธ์ž๋ฅผ ์ฐพ์€ ์ˆ˜์™€ ๋™์ผํ•˜๋‹ค.

 

 

for ๋ฌธ์œผ๋กœ ๋‚˜ํƒ€๋‚ด๋ฉด ์ด๋ ‡๋‹ค. 

function solution(myString, pat) {
    let count = 0;
    for (let i = 0; i <= myString.length - pat.length; i++) {
        if (myString.slice(i, i + pat.length) === pat) {
            count++;
        }
    }

    return count;
}

 

์ด์ „์— reduce ๋ฅผ ์‚ฌ์šฉํ•  ๋• ๋ฐฐ์—ด ์ „์ฒด์˜ ์ˆ˜๋ฅผ ํ•ฉ์ณ์•ผ ํ•œ๋‹ค๋˜์ง€ ํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ–์— ์•ˆ์จ๋ดค๋Š”๋ฐ, 

์ด๋ ‡๊ฒŒ๋„ ํ™œ์šฉํ•  ์ˆ˜ ์žˆ๊ตฌ๋‚˜.. ์ƒˆ์‚ผ ๊นจ๋‹ฌ์•˜๋‹ค.

 

์š”์ฆ˜ ๋ฌธ์ œ๊ฐ€ ์ž˜ ์•ˆํ’€๋ฆฌ๋Š”๋ฐ

๋„ˆ๋ฌด ๋ณต์žกํ•˜๊ฒŒ ์ƒ๊ฐ ๋ง๊ณ , ๋‹จ์ˆœํ•˜๊ฒŒ ์ƒ๊ฐํ•˜๋˜ ๋งŽ์ด ๋ฐฐ์šฐ์ž,,

728x90
๋ฐ˜์‘ํ˜•