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

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

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

728x90
function solution(my_string, m, c) {
    let result = "";
    for (let i = 0; i < my_string.length; i++) {
        if (i % m === c - 1) result += [...my_string][i]
    }
 return result;
}

index ๋ฅผ m ์œผ๋กœ ๋‚˜๋ˆด์„ ๋•Œ ๋‚˜๋จธ์ง€๊ฐ€ c-1 ์ด ๋˜๋ฉด ๋ฌธ์ œ์—์„œ ์›ํ•˜๋Š” index ์ด๋ฏ€๋กœ [...mystring]์˜ i ์ธ๋ฑ์Šค๋ฅผ ๊ฐ€์ง„ ๋ฌธ์ž๋ฅผ result ์— ํ•ฉ์ณ์ค€๋‹ค.

 

๋‹ค์–‘ํ•œ ๋ฐฉ๋ฒ•๋“ค์ด ์žˆ์–ด ๊ฐ€์ ธ์™”๋‹ค.

 

๐Ÿป filter ์—์„œ๋„ index ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

function solution(my_string, m, c) {
    return [...my_string].filter((_, i) => i % m === c - 1).join('');
}

 

๐Ÿป string ๋„ reduce ๋กœ ํ•ฉ์น˜๊ธฐ๊ฐ€ ๊ฐ€๋Šฅํ•˜๋‹ค. (๊ตณ์ด ๊ณ ์ฐจํ•จ์ˆ˜๋ฅผ ์จ์•ผํ•œ๋‹ค๋ฉด)

function solution(my_string, m, c) {
    return Array.from(my_string).reduce((word, v, i) => {
        return i % m + 1 === c ? word + v : word
    }, '')
}

 

728x90
๋ฐ˜์‘ํ˜•