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

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

[์•Œ๊ณ ๋ฆฌ์ฆ˜ || ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํŠน๋ณ„ํ•œ ์ด์ฐจ์› ๋ฐฐ์—ด 1

728x90
function solution(n) {
    const arr = new Array(n).fill(new Array(n).fill(0));
    for (let i = 0; i < n; i++) {
        arr[i][i] = 1;
    }
    console.log(arr)
}

์ฒ˜์Œ์— fill ์„ ํ†ตํ•ด 2์ฐจ์› ๋ฐฐ์—ด์„ ๋งŒ๋“  ํ›„, 

[i][i] ์ฐจ์› ์ˆ˜๊ฐ€ ๊ฐ™์€ ๊ฒƒ๋“ค๋งŒ 1์„ ๋„ฃ์–ด์ฃผ๋ฉด ๋˜๊ฒ ๋‹ค ์ƒ๊ฐ์„ ํ–ˆ๋Š”๋ฐ ์™ ๊ฑธ

[ [ 1, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 1 ] ] ์ด ์•„๋‹ˆ๋ผ
[ [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ] ] ๊ฐ€ ๋‚˜์˜ด

 

 

์•— ๊ทธ๋ ‡๋‹ค,, ๋ฐฐ์—ด์ด ๋œป๋Œ€๋กœ ์•ˆ๋˜๋ฉด ์–•์€ ๋ฐฐ์—ด์ผ ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ์ƒ๊ฐ์„ ๋ชปํ–ˆ๋‹ค.

 

 

์ฆ‰, 2์ฐจ์› ๋ฐฐ์—ด์ด ๊ฐ ์š”์†Œ๋กœ ๊ฐ€์ง€๊ณ  ์žˆ๋˜ [0,0,0] ์ด ๋ชจ๋‘ ๊ฐ™์€ ์ฃผ์†Œ๋ฅผ ์ฐธ์กฐํ•˜๊ณ  ์žˆ์—ˆ๊ธฐ ๋•Œ๋ฌธ์—, 

for ๋ฌธ์ด ๋Œ์•„๊ฐˆ ๋•Œ, [0][0] ์— 1์ด ๋“ค์–ด๊ฐ€๋ฉด index 1, 2์— ์žˆ๋˜ ๋ชจ๋“  ์›์†Œ๋“ค๋„ ๋˜‘๊ฐ™์ด ๋ฐ”๋€Œ์—ˆ๋˜ ๊ฒƒ์ด๋‹ค. 

 

 

fill ๋Œ€์‹  from ์„ ์‚ฌ์šฉํ•˜๊ธฐ๋ฅผ ์ถ”์ฒœ๋ฐ›์Œ.

function solution(n) {
    const arr = Array.from({length: n}, () => new Array(n).fill(0));
    for (let i = 0; i < n; i++) {
        arr[i][i] = 1;
    }
    console.log(arr)
}

 

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/from

 

Array.from() - JavaScript | MDN

Array.from() ๋ฉ”์„œ๋“œ๋Š” ์œ ์‚ฌ ๋ฐฐ์—ด ๊ฐ์ฒด(array-like object)๋‚˜ ๋ฐ˜๋ณต ๊ฐ€๋Šฅํ•œ ๊ฐ์ฒด(iterable object)๋ฅผ ์–•๊ฒŒ ๋ณต์‚ฌํ•ด ์ƒˆ๋กœ์šดArray ๊ฐ์ฒด๋ฅผ ๋งŒ๋“ญ๋‹ˆ๋‹ค.

developer.mozilla.org

 

from ์€ ๋ญ”๊ฐ€ ํ™œ์šฉ๋„๊ฐ€ ๋†’์•„๋ณด์ธ๋‹ค!

์“ฐ๋Š” ๋ฐฉ์‹์ด ์—ฌ๋Ÿฌ๊ฐœ๋ผ ์œ ์˜ํ•ด์„œ ์จ์•ผ๊ฒ ๋‹ค.

 

 

728x90
๋ฐ˜์‘ํ˜•