dlehdanakf / Codingtest-Study

알고리즘 코딩테스트 토막지식 정리
1 stars 0 forks source link

Array, Matrix #4

Open dlehdanakf opened 3 years ago

dlehdanakf commented 3 years ago

배열 만들기

const n = 100000;

console.time('A');
const a = [];
for(let i = 0; i < n; i++) a.push(0);
console.timeEnd('A');

console.time('B');
const b = new Array(n).fill(0);
console.timeEnd('B');

// A: 45.643ms
// B: 1.554ms
const n = 100000;

console.time('A');
const a = [];
for(let i = 0; i < n; i++) a.push(new Map);
console.timeEnd('A');

console.time('B');
const b = new Array(n).fill(undefined).map(_ => new Map);
console.timeEnd('B');

console.time('C');
const c = [...Array(n)].map(_ => new Map);
console.timeEnd('C');

console.time('D');
const d = new Array(n);
for(let i = 0; i < n; i++) d[i] = new Map;
console.timeEnd('D');

// A: 25.649ms
// B: 22.422ms
// C: 35.954ms
// D: 22.157ms
A: 13.806ms
B: 3.195ms
C: 7.350ms
D: 10.878ms

행렬 회전시키기

const rotate = matrix => {
  return matrix.map((row, i) =>
    row.map((val, j) => matrix[matrix.length - 1 - j][i])
  );
};
dlehdanakf commented 3 years ago

원소를 모두 더했을 때 n 이 되는 배열

const make = (target, length, sum = 0, trace = []) => {
    if(sum === target && trace.length === length) {
        console.log(trace);
    }
    if(trace.length >= length) {
        return;
    }

    const last = trace[trace.length - 1] || 1;
    const remain = target - sum;
    for(let i = last; i <= remain; i++) {
        make(target, length, sum + i, [...trace, i]);
    }
};
dlehdanakf commented 3 years ago

Transpose

const transpose = matrix => {
    const r = matrix.length, 
          c = matrix[0].length, 
          results = new Array(c).fill(undefined).map(_ => new Array(r));

    matrix.forEach((m, i) => m.forEach((n, j) => results[j][i] = n));
    return results;
};