잡다로그

[JS/코테] 코테용 기초 문법 - 배열, BFS 등 본문

Algorithm

[JS/코테] 코테용 기초 문법 - 배열, BFS 등

날으는다람쥐 2024. 5. 24. 17:55
// 기초 문법

// 배열
let arr = Array(50).fill(0)
let arr2 = Array(3).fill().map(e => Array(50).fill(0))

// 스와핑(구조분해)
[arr[1], arr[3]] = [[arr[3], arr[1]]]

// 정렬
let numbers = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers = numbers.sort((a, b) => a - b)
// 내림차순
let numbers2 = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
numbers2 = numbers.sort((a, b) => (a - b) - 1)

// 필터링
const ret = numbers.filter(e => e % 2 == 0)
const ret2 = numbers.map(e => e * 2)

let b = []
for (let a of numbers) {
    b.push(a * a)
    a * a
}

// 새로운 배열 & 배열로 연산한 값
const ret3 = numbers.reduce((total, e) => total + e, 0)

var map = new Map();
map.set(1, "value1");
map.set(2, "value2");
console.log(map.get(2));    // value2 반환
console.log(map.has(2));    // true 반환
map.delete(2);
console.lod(map.size);

// 객체 자료형
let user1 = new Object();   // 생성자 문법
let user2 = {};              // 리터럴 문법. 주로 사용하는 방식
let user = {
    name: "John",
    age: 30
};
console.log(user.name);      // John 반환
delete user.age;


// 객체 순회
for (let [key, value] of map) {
    console.log(value.id);
}

// DFS
const graph = {
    1: [2, 3],      // 1의 자식 노드가 2, 3
    2: [4],
    3: [4, 5],
    4: [],
    5: []
};

const dfs = (here, visited = new Set()) => {
    if (visited.has(here)) return
    visited.add(here)
    graph[here].forEach(e => dfs(e, visited))
}

dfs(1);

// bfs
const BFS = (graph, startNode) => {
    let visited = [];
    let needVisit = [];

    needVisit.push(startNode);  // 노드 탐색 시작

    while (needVisit.length !== 0) {
        const node = needVisit.shift(); // 가장 오래 남아있던 정점

        if (!visited.includes(node)) {
            visited.push(node);
            needVisit = [...needVisit, ...graph[node]];
        }
    }

    return visited;
}

// 이진탐색
const a = [1, 2, 3, 4, 5, 6, 7, 8]
const bs = () => {
    let lo = 0
    let hi = a.length - 1

    const target = 3

    while (lo <= hi) {
        let mid = Meth.floor((lo + hi) / 2)
        if (a[mid] == target) {
            console.log(target)     // target을 찾았을 때
            return
        } else if (a[mid] > target) {
            hi = mid - 1
        } else {
            lo = mid + 1
        }
    }
    console.log(-1)   // target이 없을 때
    return -1
}
// bs()     // 함수 선언


// 피보나치 - DP의 대표적인 예제
const fibo = (idx, memo = {}) => {
    if (idx <= 2) return 1
    if (idx in memo) return memo[idx]
    memo[idx] = fibo(idx - 1, memo) + fibo(idx - 2, memo)
    return
}
const retFibo = fibo(10)
Comments