feat(ko): add the Korean online edition (#2006)

* feat(ko): add the complete Korean online edition

* Use UTF-8 for Python CI output on Windows

* Remove print-book promotion from the Korean site

* fix(ko): preserve emphasis before Korean particles
This commit is contained in:
Yudong Jin
2026-10-29 03:46:43 +08:00
committed by GitHub
parent 71a773df64
commit 2f561d3d51
2072 changed files with 110884 additions and 102 deletions

View File

@@ -0,0 +1,6 @@
{
"tabWidth": 4,
"useTabs": false,
"semi": true,
"singleQuote": true
}

View File

@@ -0,0 +1,97 @@
/**
* File: array.js
* Created Time: 2022-11-27
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 원소에 임의 접근 */
function randomAccess(nums) {
// 구간 [0, nums.length)에서 숫자 하나를 무작위로 뽑는다
const random_index = Math.floor(Math.random() * nums.length);
// 무작위 원소를 가져와 반환한다
const random_num = nums[random_index];
return random_num;
}
/* 배열 길이 확장 */
// JavaScript의 Array는 동적 배열이므로 직접 확장할 수 있다
// 학습의 편의를 위해 이 함수에서는 Array를 길이가 고정된 배열로 취급한다
function extend(nums, enlarge) {
// 길이를 확장한 배열을 초기화한다
const res = new Array(nums.length + enlarge).fill(0);
// 원래 배열의 모든 원소를 새 배열에 복사한다
for (let i = 0; i < nums.length; i++) {
res[i] = nums[i];
}
// 확장한 새 배열을 반환한다
return res;
}
/* 배열의 인덱스 index에 원소 num 삽입 */
function insert(nums, num, index) {
// 인덱스 index와 그 뒤에 있는 모든 원소를 한 칸씩 뒤로 이동한다
for (let i = nums.length - 1; i > index; i--) {
nums[i] = nums[i - 1];
}
// index 위치의 원소에 num을 대입한다
nums[index] = num;
}
/* 인덱스 index에 있는 원소 삭제 */
function remove(nums, index) {
// 인덱스 index 뒤에 있는 모든 원소를 한 칸씩 앞으로 이동한다
for (let i = index; i < nums.length - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* 배열 순회 */
function traverse(nums) {
let count = 0;
// 인덱스를 통해 배열을 순회한다
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
// 배열의 원소를 직접 순회한다
for (const num of nums) {
count += num;
}
}
/* 배열에서 지정한 원소 탐색 */
function find(nums, target) {
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) return i;
}
return -1;
}
/* 실행 코드 */
/* 배열 초기화 */
const arr = new Array(5).fill(0);
console.log('배열 arr =', arr);
let nums = [1, 3, 2, 5, 4];
console.log('배열 nums =', nums);
/* 임의 접근 */
let random_num = randomAccess(nums);
console.log('nums에서 무작위로 가져온 원소', random_num);
/* 길이 확장 */
nums = extend(nums, 3);
console.log('배열 길이를 8로 확장한 후 nums =', nums);
/* 원소 삽입 */
insert(nums, 6, 3);
console.log('인덱스 3에 숫자 6을 삽입한 후 nums =', nums);
/* 원소 삭제 */
remove(nums, 2);
console.log('인덱스 2의 원소를 삭제한 후 nums =', nums);
/* 배열 순회 */
traverse(nums);
/* 원소 탐색 */
let index = find(nums, 3);
console.log('nums에서 원소 3을 탐색하여 얻은 인덱스 =', index);

View File

@@ -0,0 +1,82 @@
/**
* File: linked_list.js
* Created Time: 2022-12-12
* Author: IsChristina (christinaxia77@foxmail.com), Justin (xiefahit@gmail.com)
*/
const { printLinkedList } = require('../modules/PrintUtil');
const { ListNode } = require('../modules/ListNode');
/* 연결 리스트의 노드 n0 뒤에 노드 P 삽입 */
function insert(n0, P) {
const n1 = n0.next;
P.next = n1;
n0.next = P;
}
/* 연결 리스트의 노드 n0 바로 뒤에 있는 노드 삭제 */
function remove(n0) {
if (!n0.next) return;
// n0 -> P -> n1
const P = n0.next;
const n1 = P.next;
n0.next = n1;
}
/* 연결 리스트에서 인덱스가 index인 노드에 접근 */
function access(head, index) {
for (let i = 0; i < index; i++) {
if (!head) {
return null;
}
head = head.next;
}
return head;
}
/* 연결 리스트에서 값이 target인 첫 번째 노드 탐색 */
function find(head, target) {
let index = 0;
while (head !== null) {
if (head.val === target) {
return index;
}
head = head.next;
index += 1;
}
return -1;
}
/* 실행 코드 */
/* 연결 리스트 초기화 */
// 각 노드를 초기화한다
const n0 = new ListNode(1);
const n1 = new ListNode(3);
const n2 = new ListNode(2);
const n3 = new ListNode(5);
const n4 = new ListNode(4);
// 노드 사이의 참조를 설정한다
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
console.log('초기화한 연결 리스트');
printLinkedList(n0);
/* 노드 삽입 */
insert(n0, new ListNode(0));
console.log('노드를 삽입한 후의 연결 리스트');
printLinkedList(n0);
/* 노드 삭제 */
remove(n0);
console.log('노드를 삭제한 후의 연결 리스트');
printLinkedList(n0);
/* 노드 접근 */
const node = access(n0, 3);
console.log('연결 리스트에서 인덱스 3에 있는 노드의 값 = ' + node.val);
/* 노드 탐색 */
const index = find(n0, 2);
console.log('연결 리스트에서 값이 2인 노드의 인덱스 = ' + index);

View File

@@ -0,0 +1,57 @@
/**
* File: list.js
* Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com)
*/
/* 리스트 초기화 */
const nums = [1, 3, 2, 5, 4];
console.log(`리스트 nums = ${nums}`);
/* 원소 접근 */
const num = nums[1];
console.log(`인덱스 1의 원소에 접근하여 얻은 num = ${num}`);
/* 원소 갱신 */
nums[1] = 0;
console.log(`인덱스 1의 원소를 0으로 갱신한 후 nums = ${nums}`);
/* 리스트 비우기 */
nums.length = 0;
console.log(`리스트를 비운 후 nums = ${nums}`);
/* 맨 뒤에 원소 추가 */
nums.push(1);
nums.push(3);
nums.push(2);
nums.push(5);
nums.push(4);
console.log(`원소를 추가한 후 nums = ${nums}`);
/* 중간에 원소 삽입 */
nums.splice(3, 0, 6);
console.log(`인덱스 3에 숫자 6을 삽입한 후 nums = ${nums}`);
/* 원소 삭제 */
nums.splice(3, 1);
console.log(`인덱스 3의 원소를 삭제한 후 nums = ${nums}`);
/* 인덱스를 통해 리스트를 순회한다 */
let count = 0;
for (let i = 0; i < nums.length; i++) {
count += nums[i];
}
/* 리스트의 원소를 직접 순회한다 */
count = 0;
for (const x of nums) {
count += x;
}
/* 두 리스트 연결 */
const nums1 = [6, 8, 7, 10, 9];
nums.push(...nums1);
console.log(`리스트 nums1을 nums 뒤에 연결한 후 nums = ${nums}`);
/* 리스트 정렬 */
nums.sort((a, b) => a - b);
console.log(`리스트를 정렬한 후 nums = ${nums}`);

View File

@@ -0,0 +1,141 @@
/**
* File: my_list.js
* Created Time: 2022-12-12
* Author: Justin (xiefahit@gmail.com)
*/
/* 리스트 클래스 */
class MyList {
#arr = new Array(); // 배열(리스트 원소 저장)
#capacity = 10; // 리스트 용량
#size = 0; // 리스트 길이(현재 원소 개수)
#extendRatio = 2; // 리스트의 용량을 확장할 때마다 적용하는 배수
/* 생성자 */
constructor() {
this.#arr = new Array(this.#capacity);
}
/* 리스트 길이(현재 원소 개수) 반환*/
size() {
return this.#size;
}
/* 리스트 용량 반환 */
capacity() {
return this.#capacity;
}
/* 원소 접근 */
get(index) {
// 인덱스가 범위를 벗어나면 예외를 발생시킨다. 아래에서도 동일하다
if (index < 0 || index >= this.#size) throw new Error('인덱스가 범위를 벗어났다');
return this.#arr[index];
}
/* 원소 갱신 */
set(index, num) {
if (index < 0 || index >= this.#size) throw new Error('인덱스가 범위를 벗어났다');
this.#arr[index] = num;
}
/* 맨 뒤에 원소 추가 */
add(num) {
// 길이가 용량과 같으면 용량을 확장해야 한다
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// 새 원소를 리스트 맨 뒤에 추가한다
this.#arr[this.#size] = num;
this.#size++;
}
/* 중간에 원소 삽입 */
insert(index, num) {
if (index < 0 || index >= this.#size) throw new Error('인덱스가 범위를 벗어났다');
// 원소 개수가 용량을 초과하면 용량 확장을 수행한다
if (this.#size === this.#capacity) {
this.extendCapacity();
}
// 인덱스 index와 그 뒤의 원소를 모두 한 칸씩 뒤로 이동한다
for (let j = this.#size - 1; j >= index; j--) {
this.#arr[j + 1] = this.#arr[j];
}
// 원소 개수를 갱신한다
this.#arr[index] = num;
this.#size++;
}
/* 원소 삭제 */
remove(index) {
if (index < 0 || index >= this.#size) throw new Error('인덱스가 범위를 벗어났다');
let num = this.#arr[index];
// 인덱스 index 뒤의 원소를 모두 한 칸씩 앞으로 이동한다
for (let j = index; j < this.#size - 1; j++) {
this.#arr[j] = this.#arr[j + 1];
}
// 원소 개수를 갱신한다
this.#size--;
// 삭제한 원소를 반환한다
return num;
}
/* 리스트 용량 확장 */
extendCapacity() {
// 길이가 원래 배열의 extendRatio배인 새 배열을 생성하고, 원래 배열을 새 배열에 복사한다
this.#arr = this.#arr.concat(
new Array(this.capacity() * (this.#extendRatio - 1))
);
// 리스트 용량을 갱신한다
this.#capacity = this.#arr.length;
}
/* 리스트를 배열로 변환 */
toArray() {
let size = this.size();
// 유효한 길이 범위 안의 리스트 원소만 변환한다
const arr = new Array(size);
for (let i = 0; i < size; i++) {
arr[i] = this.get(i);
}
return arr;
}
}
/* 실행 코드 */
/* 리스트 초기화 */
const nums = new MyList();
/* 맨 뒤에 원소 추가 */
nums.add(1);
nums.add(3);
nums.add(2);
nums.add(5);
nums.add(4);
console.log(
`리스트 nums = ${nums.toArray()}, 용량 = ${nums.capacity()}, 길이 = ${nums.size()}`
);
/* 중간에 원소 삽입 */
nums.insert(3, 6);
console.log(`인덱스 3에 숫자 6을 삽입한 후 nums = ${nums.toArray()}`);
/* 원소 삭제 */
nums.remove(3);
console.log(`인덱스 3의 원소를 삭제한 후 nums = ${nums.toArray()}`);
/* 원소 접근 */
const num = nums.get(1);
console.log(`인덱스 1의 원소에 접근하여 얻은 num = ${num}`);
/* 원소 갱신 */
nums.set(1, 0);
console.log(`인덱스 1의 원소를 0으로 갱신한 후 nums = ${nums.toArray()}`);
/* 용량 확장 동작 테스트 */
for (let i = 0; i < 10; i++) {
// i = 5일 때 리스트 길이가 용량을 초과하므로 용량 확장이 수행된다
nums.add(i);
}
console.log(
`용량을 확장한 후 리스트 nums = ${nums.toArray()}, 용량 = ${nums.capacity()}, 길이 = ${nums.size()}`
);

View File

@@ -0,0 +1,55 @@
/**
* File: n_queens.js
* Created Time: 2023-05-13
* Author: Justin (xiefahit@gmail.com)
*/
/* 백트래킹 알고리즘: n-퀸 */
function backtrack(row, n, state, res, cols, diags1, diags2) {
// 모든 행에 배치했으면 해를 기록한다
if (row === n) {
res.push(state.map((row) => row.slice()));
return;
}
// 모든 열을 순회한다
for (let col = 0; col < n; col++) {
// 해당 칸이 속한 주대각선과 부대각선을 계산한다
const diag1 = row - col + n - 1;
const diag2 = row + col;
// 가지치기: 해당 칸이 속한 열, 주대각선, 부대각선에 퀸이 있으면 안 된다
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
// 시도: 해당 칸에 퀸을 놓는다
state[row][col] = 'Q';
cols[col] = diags1[diag1] = diags2[diag2] = true;
// 다음 행에 배치한다
backtrack(row + 1, n, state, res, cols, diags1, diags2);
// 되돌리기: 해당 칸을 빈칸으로 되돌린다
state[row][col] = '#';
cols[col] = diags1[diag1] = diags2[diag2] = false;
}
}
}
/* n-퀸 문제 풀기 */
function nQueens(n) {
// n*n 크기의 체스판을 초기화한다. 'Q'는 퀸, '#'은 빈칸을 나타낸다
const state = Array.from({ length: n }, () => Array(n).fill('#'));
const cols = Array(n).fill(false); // 열에 퀸이 있는지 기록한다
const diags1 = Array(2 * n - 1).fill(false); // 주대각선에 퀸이 있는지 기록한다
const diags2 = Array(2 * n - 1).fill(false); // 부대각선에 퀸이 있는지 기록한다
const res = [];
backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
// 실행 코드
const n = 4;
const res = nQueens(n);
console.log(`입력한 체스판의 가로와 세로 길이: ${n}`);
console.log(`퀸을 배치하는 방법은 총 ${res.length}가지이다`);
res.forEach((state) => {
console.log('--------------------');
state.forEach((row) => console.log(row));
});

View File

@@ -0,0 +1,42 @@
/**
* File: permutations_i.js
* Created Time: 2023-05-13
* Author: Justin (xiefahit@gmail.com)
*/
/* 백트래킹 알고리즘: 모든 순열 I */
function backtrack(state, choices, selected, res) {
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 모든 선택지를 순회한다
choices.forEach((choice, i) => {
// 가지치기: 원소를 중복하여 선택할 수 없다
if (!selected[i]) {
// 시도: 선택하고 상태를 갱신한다
selected[i] = true;
state.push(choice);
// 다음 선택을 진행한다
backtrack(state, choices, selected, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = false;
state.pop();
}
});
}
/* 모든 순열 I */
function permutationsI(nums) {
const res = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
// 실행 코드
const nums = [1, 2, 3];
const res = permutationsI(nums);
console.log(`입력 배열 nums = ${JSON.stringify(nums)}`);
console.log(`모든 순열 res = ${JSON.stringify(res)}`);

View File

@@ -0,0 +1,44 @@
/**
* File: permutations_ii.js
* Created Time: 2023-05-13
* Author: Justin (xiefahit@gmail.com)
*/
/* 백트래킹 알고리즘: 모든 순열 II */
function backtrack(state, choices, selected, res) {
// 상태의 길이가 원소 개수와 같으면 해를 기록한다
if (state.length === choices.length) {
res.push([...state]);
return;
}
// 모든 선택지를 순회한다
const duplicated = new Set();
choices.forEach((choice, i) => {
// 가지치기: 원소를 중복하여 선택할 수 없으며, 값이 같은 원소도 중복하여 선택할 수 없다
if (!selected[i] && !duplicated.has(choice)) {
// 시도: 선택하고 상태를 갱신한다
duplicated.add(choice); // 선택한 원소의 값을 기록한다
selected[i] = true;
state.push(choice);
// 다음 선택을 진행한다
backtrack(state, choices, selected, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
selected[i] = false;
state.pop();
}
});
}
/* 모든 순열 II */
function permutationsII(nums) {
const res = [];
backtrack([], nums, Array(nums.length).fill(false), res);
return res;
}
// 실행 코드
const nums = [1, 2, 2];
const res = permutationsII(nums);
console.log(`입력 배열 nums = ${JSON.stringify(nums)}`);
console.log(`모든 순열 res = ${JSON.stringify(res)}`);

View File

@@ -0,0 +1,33 @@
/**
* File: preorder_traversal_i_compact.js
* Created Time: 2023-05-09
* Author: Justin (xiefahit@gmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 전위 순회: 예제 1 */
function preOrder(root, res) {
if (root === null) {
return;
}
if (root.val === 7) {
// 해를 기록한다
res.push(root);
}
preOrder(root.left, res);
preOrder(root.right, res);
}
// 실행 코드
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화');
printTree(root);
// 전위 순회
const res = [];
preOrder(root, res);
console.log('\n값이 7인 모든 노드 출력');
console.log(res.map((node) => node.val));

View File

@@ -0,0 +1,40 @@
/**
* File: preorder_traversal_ii_compact.js
* Created Time: 2023-05-09
* Author: Justin (xiefahit@gmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 전위 순회: 예제 2 */
function preOrder(root, path, res) {
if (root === null) {
return;
}
// 시도
path.push(root);
if (root.val === 7) {
// 해를 기록한다
res.push([...path]);
}
preOrder(root.left, path, res);
preOrder(root.right, path, res);
// 되돌리기
path.pop();
}
// 실행 코드
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화');
printTree(root);
// 전위 순회
const path = [];
const res = [];
preOrder(root, path, res);
console.log('\n루트 노드에서 노드 7까지의 모든 경로 출력');
res.forEach((path) => {
console.log(path.map((node) => node.val));
});

View File

@@ -0,0 +1,41 @@
/**
* File: preorder_traversal_iii_compact.js
* Created Time: 2023-05-09
* Author: Justin (xiefahit@gmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 전위 순회: 예제 3 */
function preOrder(root, path, res) {
// 가지치기
if (root === null || root.val === 3) {
return;
}
// 시도
path.push(root);
if (root.val === 7) {
// 해를 기록한다
res.push([...path]);
}
preOrder(root.left, path, res);
preOrder(root.right, path, res);
// 되돌리기
path.pop();
}
// 실행 코드
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화');
printTree(root);
// 전위 순회
const path = [];
const res = [];
preOrder(root, path, res);
console.log('\n루트 노드에서 노드 7까지의 모든 경로 출력. 경로에는 값이 3인 노드가 포함되지 않는다');
res.forEach((path) => {
console.log(path.map((node) => node.val));
});

View File

@@ -0,0 +1,68 @@
/**
* File: preorder_traversal_iii_template.js
* Created Time: 2023-05-09
* Author: Justin (xiefahit@gmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 현재 상태가 해인지 판단 */
function isSolution(state) {
return state && state[state.length - 1]?.val === 7;
}
/* 해를 기록한다 */
function recordSolution(state, res) {
res.push([...state]);
}
/* 현재 상태에서 해당 선택이 유효한지 판단 */
function isValid(state, choice) {
return choice !== null && choice.val !== 3;
}
/* 상태 갱신 */
function makeChoice(state, choice) {
state.push(choice);
}
/* 상태 복원 */
function undoChoice(state) {
state.pop();
}
/* 백트래킹 알고리즘: 예제 3 */
function backtrack(state, choices, res) {
// 해인지 확인한다
if (isSolution(state)) {
// 해를 기록한다
recordSolution(state, res);
}
// 모든 선택지를 순회한다
for (const choice of choices) {
// 가지치기: 선택이 유효한지 확인한다
if (isValid(state, choice)) {
// 시도: 선택하고 상태를 갱신한다
makeChoice(state, choice);
// 다음 선택을 진행한다
backtrack(state, [choice.left, choice.right], res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
undoChoice(state);
}
}
}
// 실행 코드
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화');
printTree(root);
// 백트래킹 알고리즘
const res = [];
backtrack([], [root], res);
console.log('\n값이 3인 노드를 포함하지 않는 조건으로, 루트 노드에서 노드 7까지의 모든 경로 출력');
res.forEach((path) => {
console.log(path.map((node) => node.val));
});

View File

@@ -0,0 +1,46 @@
/**
* File: subset_sum_i.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 백트래킹 알고리즘: 부분 집합 합 I */
function backtrack(state, target, choices, start, res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (target === 0) {
res.push([...state]);
return;
}
// 모든 선택지를 순회한다
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
for (let i = start; i < choices.length; i++) {
// 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
// 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
if (target - choices[i] < 0) {
break;
}
// 시도: 선택하고 target, start를 갱신한다
state.push(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop();
}
}
/* 부분 집합 합 I 풀기 */
function subsetSumI(nums, target) {
const state = []; // 상태(부분 집합)
nums.sort((a, b) => a - b); // nums를 정렬한다
const start = 0; // 순회 시작 위치
const res = []; // 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res);
return res;
}
/* 실행 코드 */
const nums = [3, 4, 5];
const target = 9;
const res = subsetSumI(nums, target);
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);

View File

@@ -0,0 +1,44 @@
/**
* File: subset_sum_i_naive.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 백트래킹 알고리즘: 부분 집합 합 I */
function backtrack(state, target, total, choices, res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (total === target) {
res.push([...state]);
return;
}
// 모든 선택지를 순회한다
for (let i = 0; i < choices.length; i++) {
// 가지치기: 부분 집합의 합이 target을 초과하면 해당 선택을 건너뛴다
if (total + choices[i] > target) {
continue;
}
// 시도: 선택하고 원소의 합 total을 갱신한다
state.push(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target, total + choices[i], choices, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop();
}
}
/* 부분 집합 합 I 풀기(중복 부분 집합 포함) */
function subsetSumINaive(nums, target) {
const state = []; // 상태(부분 집합)
const total = 0; // 부분 집합의 합
const res = []; // 결과 리스트(부분 집합 리스트)
backtrack(state, target, total, nums, res);
return res;
}
/* 실행 코드 */
const nums = [3, 4, 5];
const target = 9;
const res = subsetSumINaive(nums, target);
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);
console.log('이 방법의 출력 결과에는 중복 집합이 포함된다');

View File

@@ -0,0 +1,51 @@
/**
* File: subset_sum_ii.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 백트래킹 알고리즘: 부분 집합 합 II */
function backtrack(state, target, choices, start, res) {
// 부분 집합의 합이 target과 같으면 해를 기록한다
if (target === 0) {
res.push([...state]);
return;
}
// 모든 선택지를 순회한다
// 가지치기 2: start부터 순회하여 중복 부분 집합 생성을 방지한다
// 가지치기 3: start부터 순회하여 같은 원소의 중복 선택을 방지한다
for (let i = start; i < choices.length; i++) {
// 가지치기 1: 부분 집합의 합이 target을 초과하면 즉시 반복문을 종료한다
// 배열이 정렬되어 있어 뒤의 원소가 더 크므로, 부분 집합의 합이 반드시 target을 초과하기 때문이다
if (target - choices[i] < 0) {
break;
}
// 가지치기 4: 해당 원소가 왼쪽 원소와 같으면 탐색 분기가 중복되므로 바로 건너뛴다
if (i > start && choices[i] === choices[i - 1]) {
continue;
}
// 시도: 선택하고 target, start를 갱신한다
state.push(choices[i]);
// 다음 선택을 진행한다
backtrack(state, target - choices[i], choices, i + 1, res);
// 되돌리기: 선택을 취소하고 이전 상태로 되돌린다
state.pop();
}
}
/* 부분 집합 합 II 풀기 */
function subsetSumII(nums, target) {
const state = []; // 상태(부분 집합)
nums.sort((a, b) => a - b); // nums를 정렬한다
const start = 0; // 순회 시작 위치
const res = []; // 결과 리스트(부분 집합 리스트)
backtrack(state, target, nums, start, res);
return res;
}
/* 실행 코드 */
const nums = [4, 4, 5];
const target = 9;
const res = subsetSumII(nums, target);
console.log(`입력 배열 nums = ${JSON.stringify(nums)}, target = ${target}`);
console.log(`합이 ${target}인 모든 부분 집합 res = ${JSON.stringify(res)}`);

View File

@@ -0,0 +1,63 @@
/**
* File: complexity_exercises.js
* Created Time: 2026-08-18
* Author: Hello Algo Team
*/
/* 반복으로 합 구하기 */
function sumIter(n) {
let res = 0;
for (let i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* 재귀로 합 구하기 */
function sumRecur(n) {
if (n === 1) {
return 1;
}
return n + sumRecur(n - 1);
}
/* 선형 차수 반복문 */
function linearLoop(n) {
let res = 0;
for (let i = 0; i < n; i++) {
res += i;
}
return res;
}
/* 제곱 차수 반복문 */
function quadraticLoop(n) {
let res = 0;
for (let i = 0; i < n; i++) {
for (let j = i; j < n; j++) {
res += j;
}
}
return res;
}
/* 로그 차수 반복문 */
function logarithmicLoop(n) {
while (n > 1) {
n = Math.floor(n / 2);
}
return n;
}
if (
sumIter(1) !== 1 ||
sumRecur(1) !== 1 ||
sumIter(4) !== 10 ||
sumRecur(4) !== 10 ||
linearLoop(4) !== 6 ||
quadraticLoop(4) !== 20 ||
logarithmicLoop(4) !== 1 ||
logarithmicLoop(5) !== 1
) {
throw new Error('복잡도 연습 문제 검증에 실패했다');
}

View File

@@ -0,0 +1,70 @@
/**
* File: iteration.js
* Created Time: 2023-08-28
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* for 반복문 */
function forLoop(n) {
let res = 0;
// 반복문으로 1, 2, ..., n-1, n의 합을 구한다
for (let i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* while 반복문 */
function whileLoop(n) {
let res = 0;
let i = 1; // 조건 변수를 초기화한다
// 반복문으로 1, 2, ..., n-1, n의 합을 구한다
while (i <= n) {
res += i;
i++; // 조건 변수를 갱신한다
}
return res;
}
/* while 반복문(두 번 갱신) */
function whileLoopII(n) {
let res = 0;
let i = 1; // 조건 변수를 초기화한다
// 반복문으로 1, 4, 10, ...의 합을 구한다
while (i <= n) {
res += i;
// 조건 변수를 갱신한다
i++;
i *= 2;
}
return res;
}
/* 이중 for 반복문 */
function nestedForLoop(n) {
let res = '';
// i = 1, 2, ..., n-1, n을 반복한다
for (let i = 1; i <= n; i++) {
// j = 1, 2, ..., n-1, n을 반복한다
for (let j = 1; j <= n; j++) {
res += `(${i}, ${j}), `;
}
}
return res;
}
/* 실행 코드 */
const n = 5;
let res;
res = forLoop(n);
console.log(`for 반복문으로 구한 합 res = ${res}`);
res = whileLoop(n);
console.log(`while 반복문으로 구한 합 res = ${res}`);
res = whileLoopII(n);
console.log(`while 반복문(두 번 갱신)으로 구한 합 res = ${res}`);
const resStr = nestedForLoop(n);
console.log(`이중 for 반복문의 순회 결과 ${resStr}`);

View File

@@ -0,0 +1,69 @@
/**
* File: recursion.js
* Created Time: 2023-08-28
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 재귀 */
function recur(n) {
// 종료 조건
if (n === 1) return 1;
// 내려가기: 재귀 호출
const res = recur(n - 1);
// 돌아오기: 결과 반환
return n + res;
}
/* 반복으로 재귀 구현 */
function forLoopRecur(n) {
// 명시적인 스택을 사용하여 시스템 호출 스택을 모방한다
const stack = [];
let res = 0;
// 내려가기: 재귀 호출
for (let i = n; i > 0; i--) {
// 스택에 삽입하여 내려가는 과정을 모방한다
stack.push(i);
}
// 돌아오기: 결과 반환
while (stack.length) {
// 스택에서 꺼내어 돌아오는 과정을 모방한다
res += stack.pop();
}
// res = 1+2+3+...+n
return res;
}
/* 꼬리 재귀 */
function tailRecur(n, res) {
// 종료 조건
if (n === 0) return res;
// 꼬리 재귀 호출
return tailRecur(n - 1, res + n);
}
/* 피보나치 수열: 재귀 */
function fib(n) {
// 종료 조건 f(1) = 0, f(2) = 1
if (n === 1 || n === 2) return n - 1;
// 재귀 호출 f(n) = f(n-1) + f(n-2)
const res = fib(n - 1) + fib(n - 2);
// 결과 f(n)을 반환한다
return res;
}
/* 실행 코드 */
const n = 5;
let res;
res = recur(n);
console.log(`재귀 함수로 구한 합 res = ${res}`);
res = forLoopRecur(n);
console.log(`반복으로 재귀를 구현하여 구한 합 res = ${res}`);
res = tailRecur(n, 0);
console.log(`꼬리 재귀 함수로 구한 합 res = ${res}`);
res = fib(n);
console.log(`피보나치 수열의 ${n}번째 항은 ${res}이다`);

View File

@@ -0,0 +1,103 @@
/**
* File: space_complexity.js
* Created Time: 2023-02-05
* Author: Justin (xiefahit@gmail.com)
*/
const { ListNode } = require('../modules/ListNode');
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 함수 */
function constFunc() {
// 몇 가지 연산을 수행한다
return 0;
}
/* 상수 차수 */
function constant(n) {
// 상수, 변수, 객체는 O(1) 공간을 차지한다
const a = 0;
const b = 0;
const nums = new Array(10000);
const node = new ListNode(0);
// 반복문 안의 변수는 O(1) 공간을 차지한다
for (let i = 0; i < n; i++) {
const c = 0;
}
// 반복문 안의 함수는 O(1) 공간을 차지한다
for (let i = 0; i < n; i++) {
constFunc();
}
}
/* 선형 차수 */
function linear(n) {
// 길이가 n인 배열은 O(n) 공간을 차지한다
const nums = new Array(n);
// 길이가 n인 리스트는 O(n) 공간을 차지한다
const nodes = [];
for (let i = 0; i < n; i++) {
nodes.push(new ListNode(i));
}
// 길이가 n인 해시 테이블은 O(n) 공간을 차지한다
const map = new Map();
for (let i = 0; i < n; i++) {
map.set(i, i.toString());
}
}
/* 선형 차수(재귀 구현) */
function linearRecur(n) {
console.log(`재귀 n = ${n}`);
if (n === 1) return;
linearRecur(n - 1);
}
/* 제곱 차수 */
function quadratic(n) {
// 행렬은 O(n^2) 공간을 차지한다
const numMatrix = Array(n)
.fill(null)
.map(() => Array(n).fill(null));
// 이차원 리스트는 O(n^2) 공간을 차지한다
const numList = [];
for (let i = 0; i < n; i++) {
const tmp = [];
for (let j = 0; j < n; j++) {
tmp.push(0);
}
numList.push(tmp);
}
}
/* 제곱 차수(재귀 구현) */
function quadraticRecur(n) {
if (n <= 0) return 0;
const nums = new Array(n);
console.log(`재귀 n = ${n}일 때 nums의 길이 = ${nums.length}`);
return quadraticRecur(n - 1);
}
/* 지수 차수(포화 이진 트리 구성) */
function buildTree(n) {
if (n === 0) return null;
const root = new TreeNode(0);
root.left = buildTree(n - 1);
root.right = buildTree(n - 1);
return root;
}
/* 실행 코드 */
const n = 5;
// 상수 차수
constant(n);
// 선형 차수
linear(n);
linearRecur(n);
// 제곱 차수
quadratic(n);
quadraticRecur(n);
// 지수 차수
const root = buildTree(n);
printTree(root);

View File

@@ -0,0 +1,155 @@
/**
* File: time_complexity.js
* Created Time: 2023-01-02
* Author: RiverTwilight (contact@rene.wang)
*/
/* 상수 차수 */
function constant(n) {
let count = 0;
const size = 100000;
for (let i = 0; i < size; i++) count++;
return count;
}
/* 선형 차수 */
function linear(n) {
let count = 0;
for (let i = 0; i < n; i++) count++;
return count;
}
/* 선형 차수(배열 순회) */
function arrayTraversal(nums) {
let count = 0;
// 반복 횟수는 배열 길이에 비례한다
for (let i = 0; i < nums.length; i++) {
count++;
}
return count;
}
/* 제곱 차수 */
function quadratic(n) {
let count = 0;
// 반복 횟수는 데이터 크기 n의 제곱에 비례한다
for (let i = 0; i < n; i++) {
for (let j = 0; j < n; j++) {
count++;
}
}
return count;
}
/* 제곱 차수(버블 정렬) */
function bubbleSort(nums) {
let count = 0; // 카운터
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (let i = nums.length - 1; i > 0; i--) {
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
count += 3; // 원소 교환에는 단위 연산 3회가 포함된다
}
}
}
return count;
}
/* 지수 차수(반복문 구현) */
function exponential(n) {
let count = 0,
base = 1;
// 세포가 매번 둘로 나뉘어 수열 1, 2, 4, 8, ..., 2^(n-1)을 이룬다
for (let i = 0; i < n; i++) {
for (let j = 0; j < base; j++) {
count++;
}
base *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* 지수 차수(재귀 구현) */
function expRecur(n) {
if (n === 1) return 1;
return expRecur(n - 1) + expRecur(n - 1) + 1;
}
/* 로그 차수(반복문 구현) */
function logarithmic(n) {
let count = 0;
while (n > 1) {
n = n / 2;
count++;
}
return count;
}
/* 로그 차수(재귀 구현) */
function logRecur(n) {
if (n <= 1) return 0;
return logRecur(n / 2) + 1;
}
/* 선형 로그 차수 */
function linearLogRecur(n) {
if (n <= 1) return 1;
let count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
for (let i = 0; i < n; i++) {
count++;
}
return count;
}
/* 팩토리얼 차수(재귀 구현) */
function factorialRecur(n) {
if (n === 0) return 1;
let count = 0;
// 하나에서 n개로 분열한다
for (let i = 0; i < n; i++) {
count += factorialRecur(n - 1);
}
return count;
}
/* 실행 코드 */
// n을 바꾸어 실행하면서 각 복잡도에서 연산 횟수가 어떻게 변하는지 살펴볼 수 있다
const n = 8;
console.log('입력 데이터 크기 n = ' + n);
let count = constant(n);
console.log('상수 차수의 연산 횟수 = ' + count);
count = linear(n);
console.log('선형 차수의 연산 횟수 = ' + count);
count = arrayTraversal(new Array(n));
console.log('선형 차수(배열 순회)의 연산 횟수 = ' + count);
count = quadratic(n);
console.log('제곱 차수의 연산 횟수 = ' + count);
let nums = new Array(n);
for (let i = 0; i < n; i++) nums[i] = n - i; // [n,n-1,...,2,1]
count = bubbleSort(nums);
console.log('제곱 차수(버블 정렬)의 연산 횟수 = ' + count);
count = exponential(n);
console.log('지수 차수(반복문 구현)의 연산 횟수 = ' + count);
count = expRecur(n);
console.log('지수 차수(재귀 구현)의 연산 횟수 = ' + count);
count = logarithmic(n);
console.log('로그 차수(반복문 구현)의 연산 횟수 = ' + count);
count = logRecur(n);
console.log('로그 차수(재귀 구현)의 연산 횟수 = ' + count);
count = linearLogRecur(n);
console.log('선형 로그 차수(재귀 구현)의 연산 횟수 = ' + count);
count = factorialRecur(n);
console.log('팩토리얼 차수(재귀 구현)의 연산 횟수 = ' + count);

View File

@@ -0,0 +1,43 @@
/**
* File: worst_best_time_complexity.js
* Created Time: 2023-01-05
* Author: RiverTwilight (contact@rene.wang)
*/
/* 원소가 { 1, 2, ..., n }이며 순서가 섞인 배열 생성 */
function randomNumbers(n) {
const nums = Array(n);
// 배열 nums = { 1, 2, 3, ..., n }을 생성한다
for (let i = 0; i < n; i++) {
nums[i] = i + 1;
}
// 배열 원소를 무작위로 섞는다
for (let i = 0; i < n; i++) {
const r = Math.floor(Math.random() * (i + 1));
const temp = nums[i];
nums[i] = nums[r];
nums[r] = temp;
}
return nums;
}
/* 배열 nums에서 숫자 1이 있는 인덱스 탐색 */
function findOne(nums) {
for (let i = 0; i < nums.length; i++) {
// 원소 1이 배열 맨 앞에 있으면 최선 시간 복잡도 O(1)에 도달한다
// 원소 1이 배열 맨 뒤에 있으면 최악 시간 복잡도 O(n)에 도달한다
if (nums[i] === 1) {
return i;
}
}
return -1;
}
/* 실행 코드 */
for (let i = 0; i < 10; i++) {
const n = 100;
const nums = randomNumbers(n);
const index = findOne(nums);
console.log('\n배열 [ 1, 2, ..., n ]을 섞은 결과 = [' + nums.join(', ') + ']');
console.log('숫자 1의 인덱스 ' + index);
}

View File

@@ -0,0 +1,39 @@
/**
* File: binary_search_recur.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 이진 탐색: 문제 f(i, j) */
function dfs(nums, target, i, j) {
// 구간이 비어 있으면 목표 원소가 없다는 뜻이므로 -1을 반환한다
if (i > j) {
return -1;
}
// 중간 인덱스 m을 계산한다
const m = i + ((j - i) >> 1);
if (nums[m] < target) {
// 부분 문제 f(m+1, j)를 재귀적으로 푼다
return dfs(nums, target, m + 1, j);
} else if (nums[m] > target) {
// 부분 문제 f(i, m-1)를 재귀적으로 푼다
return dfs(nums, target, i, m - 1);
} else {
// 목표 원소를 찾았으므로 해당 인덱스를 반환한다
return m;
}
}
/* 이진 탐색 */
function binarySearch(nums, target) {
const n = nums.length;
// 문제 f(0, n-1)을 푼다
return dfs(nums, target, 0, n - 1);
}
/* 실행 코드 */
const target = 6;
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
// 이진 탐색(양 끝을 포함하는 닫힌 구간)
const index = binarySearch(nums, target);
console.log(`목표 원소 6의 인덱스 = ${index}`);

View File

@@ -0,0 +1,44 @@
/**
* File: build_tree.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
const { printTree } = require('../modules/PrintUtil');
const { TreeNode } = require('../modules/TreeNode');
/* 이진 트리 구성: 분할 정복 */
function dfs(preorder, inorderMap, i, l, r) {
// 서브트리 구간이 비어 있으면 종료한다
if (r - l < 0) return null;
// 루트 노드를 초기화한다
const root = new TreeNode(preorder[i]);
// m을 조회하여 왼쪽과 오른쪽 서브트리를 나눈다
const m = inorderMap.get(preorder[i]);
// 부분 문제: 왼쪽 서브트리 구성
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
// 부분 문제: 오른쪽 서브트리 구성
root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
// 루트 노드를 반환한다
return root;
}
/* 이진 트리 구성 */
function buildTree(preorder, inorder) {
// inorder 원소와 인덱스의 대응 관계를 저장할 해시 테이블을 초기화한다
let inorderMap = new Map();
for (let i = 0; i < inorder.length; i++) {
inorderMap.set(inorder[i], i);
}
const root = dfs(preorder, inorderMap, 0, 0, inorder.length - 1);
return root;
}
/* 실행 코드 */
const preorder = [3, 9, 2, 1, 7];
const inorder = [9, 3, 1, 2, 7];
console.log('전위 순회 = ' + JSON.stringify(preorder));
console.log('중위 순회 = ' + JSON.stringify(inorder));
const root = buildTree(preorder, inorder);
console.log('구성한 이진 트리:');
printTree(root);

View File

@@ -0,0 +1,21 @@
/**
* File: fast_power.js
* Created Time: 2026-08-18
* Author: Hello Algo Team
*/
/* 빠른 거듭제곱 */
function fastPow(x, n) {
if (n === 0) {
return 1;
}
const half = fastPow(x, Math.floor(n / 2));
if (n % 2 === 0) {
return half * half;
}
return half * half * x;
}
if (fastPow(7, 0) !== 1 || fastPow(3, 5) !== 243 || fastPow(2, 6) !== 64) {
throw new Error('빠른 거듭제곱 검증에 실패했다');
}

View File

@@ -0,0 +1,52 @@
/**
* File: hanota.js
* Created Time: 2023-07-30
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 원판 하나 이동 */
function move(src, tar) {
// src의 맨 위에서 원판 하나를 꺼낸다
const pan = src.pop();
// 원판을 tar의 맨 위에 놓는다
tar.push(pan);
}
/* 하노이의 탑 문제 f(i) 풀기 */
function dfs(i, src, buf, tar) {
// src에 원판이 하나만 남아 있으면 바로 tar로 옮긴다
if (i === 1) {
move(src, tar);
return;
}
// 부분 문제 f(i-1): tar를 이용하여 src의 맨 위 원판 i-1개를 buf로 옮긴다
dfs(i - 1, src, tar, buf);
// 부분 문제 f(1): src에 남은 원판 하나를 tar로 옮긴다
move(src, tar);
// 부분 문제 f(i-1): src를 이용하여 buf의 맨 위 원판 i-1개를 tar로 옮긴다
dfs(i - 1, buf, src, tar);
}
/* 하노이의 탑 문제 풀기 */
function solveHanota(A, B, C) {
const n = A.length;
// B를 이용하여 A의 맨 위 원판 n개를 C로 옮긴다
dfs(n, A, B, C);
}
/* 실행 코드 */
// 리스트의 맨 뒤가 기둥의 맨 위이다
const A = [5, 4, 3, 2, 1];
const B = [];
const C = [];
console.log('초기 상태:');
console.log(`A = ${JSON.stringify(A)}`);
console.log(`B = ${JSON.stringify(B)}`);
console.log(`C = ${JSON.stringify(C)}`);
solveHanota(A, B, C);
console.log('원판 이동을 마친 후:');
console.log(`A = ${JSON.stringify(A)}`);
console.log(`B = ${JSON.stringify(B)}`);
console.log(`C = ${JSON.stringify(C)}`);

View File

@@ -0,0 +1,34 @@
/**
* File: climbing_stairs_backtrack.js
* Created Time: 2023-07-26
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 백트래킹 */
function backtrack(choices, state, n, res) {
// n번째 계단에 도달하면 방법의 수에 1을 더한다
if (state === n) res.set(0, res.get(0) + 1);
// 모든 선택지를 순회한다
for (const choice of choices) {
// 가지치기: n번째 계단을 넘어갈 수 없다
if (state + choice > n) continue;
// 시도: 선택하고 상태를 갱신한다
backtrack(choices, state + choice, n, res);
// 되돌리기
}
}
/* 계단 오르기: 백트래킹 */
function climbingStairsBacktrack(n) {
const choices = [1, 2]; // 한 계단 또는 두 계단 오르기를 선택할 수 있다
const state = 0; // 0번째 계단에서 오르기 시작한다
const res = new Map();
res.set(0, 0); // res[0]에 방법의 수를 기록한다
backtrack(choices, state, n, res);
return res.get(0);
}
/* 실행 코드 */
const n = 9;
const res = climbingStairsBacktrack(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);

View File

@@ -0,0 +1,30 @@
/**
* File: climbing_stairs_constraint_dp.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 제약 조건이 있는 계단 오르기: 동적 계획법 */
function climbingStairsConstraintDP(n) {
if (n === 1 || n === 2) {
return 1;
}
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
const dp = Array.from(new Array(n + 1), () => new Array(3));
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1][1] = 1;
dp[1][2] = 0;
dp[2][1] = 0;
dp[2][2] = 1;
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (let i = 3; i <= n; i++) {
dp[i][1] = dp[i - 1][2];
dp[i][2] = dp[i - 2][1] + dp[i - 2][2];
}
return dp[n][1] + dp[n][2];
}
/* 실행 코드 */
const n = 9;
const res = climbingStairsConstraintDP(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);

View File

@@ -0,0 +1,24 @@
/**
* File: climbing_stairs_dfs.js
* Created Time: 2023-07-26
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 탐색 */
function dfs(i) {
// dp[1]과 dp[2]는 이미 알고 있으므로 해당 값을 반환한다
if (i === 1 || i === 2) return i;
// dp[i] = dp[i-1] + dp[i-2]
const count = dfs(i - 1) + dfs(i - 2);
return count;
}
/* 계단 오르기: 탐색 */
function climbingStairsDFS(n) {
return dfs(n);
}
/* 실행 코드 */
const n = 9;
const res = climbingStairsDFS(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);

View File

@@ -0,0 +1,30 @@
/**
* File: climbing_stairs_dfs_mem.js
* Created Time: 2023-07-26
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 메모이제이션을 이용한 탐색 */
function dfs(i, mem) {
// dp[1]과 dp[2]는 이미 알고 있으므로 해당 값을 반환한다
if (i === 1 || i === 2) return i;
// dp[i]의 기록이 있으면 해당 값을 바로 반환한다
if (mem[i] != -1) return mem[i];
// dp[i] = dp[i-1] + dp[i-2]
const count = dfs(i - 1, mem) + dfs(i - 2, mem);
// dp[i]를 기록한다
mem[i] = count;
return count;
}
/* 계단 오르기: 메모이제이션을 이용한 탐색 */
function climbingStairsDFSMem(n) {
// mem[i]는 i번째 계단까지 오르는 전체 방법의 수를 기록하며, -1은 기록이 없음을 나타낸다
const mem = new Array(n + 1).fill(-1);
return dfs(n, mem);
}
/* 실행 코드 */
const n = 9;
const res = climbingStairsDFSMem(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);

View File

@@ -0,0 +1,40 @@
/**
* File: climbing_stairs_dp.js
* Created Time: 2023-07-26
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 계단 오르기: 동적 계획법 */
function climbingStairsDP(n) {
if (n === 1 || n === 2) return n;
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
const dp = new Array(n + 1).fill(-1);
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1] = 1;
dp[2] = 2;
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (let i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* 계단 오르기: 공간을 최적화한 동적 계획법 */
function climbingStairsDPComp(n) {
if (n === 1 || n === 2) return n;
let a = 1,
b = 2;
for (let i = 3; i <= n; i++) {
const tmp = b;
b = a + b;
a = tmp;
}
return b;
}
/* 실행 코드 */
const n = 9;
let res = climbingStairsDP(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);
res = climbingStairsDPComp(n);
console.log(`${n}개의 계단을 오르는 방법은 총 ${res}가지이다`);

View File

@@ -0,0 +1,66 @@
/**
* File: coin_change.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 동전 교환: 동적 계획법 */
function coinChangeDP(coins, amt) {
const n = coins.length;
const MAX = amt + 1;
// dp 테이블을 초기화한다
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// 상태 전이: 첫 번째 행과 첫 번째 열
for (let a = 1; a <= amt; a++) {
dp[0][a] = MAX;
}
// 상태 전이: 나머지 행과 열
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[i][a] = dp[i - 1][a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우 중 더 작은 값
dp[i][a] = Math.min(dp[i - 1][a], dp[i][a - coins[i - 1]] + 1);
}
}
}
return dp[n][amt] !== MAX ? dp[n][amt] : -1;
}
/* 동전 교환: 공간을 최적화한 동적 계획법 */
function coinChangeDPComp(coins, amt) {
const n = coins.length;
const MAX = amt + 1;
// dp 테이블을 초기화한다
const dp = Array.from({ length: amt + 1 }, () => MAX);
dp[0] = 0;
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[a] = dp[a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우 중 더 작은 값
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
}
}
}
return dp[amt] !== MAX ? dp[amt] : -1;
}
/* 실행 코드 */
const coins = [1, 2, 5];
const amt = 4;
// 동적 계획법
let res = coinChangeDP(coins, amt);
console.log(`목표 금액을 만드는 데 필요한 최소 동전 개수는 ${res}개이다`);
// 공간을 최적화한 동적 계획법
res = coinChangeDPComp(coins, amt);
console.log(`목표 금액을 만드는 데 필요한 최소 동전 개수는 ${res}개이다`);

View File

@@ -0,0 +1,64 @@
/**
* File: coin_change_ii.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 동전 교환 II: 동적 계획법 */
function coinChangeIIDP(coins, amt) {
const n = coins.length;
// dp 테이블을 초기화한다
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: amt + 1 }, () => 0)
);
// 첫 번째 열을 초기화한다
for (let i = 0; i <= n; i++) {
dp[i][0] = 1;
}
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[i][a] = dp[i - 1][a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우의 방법 수를 더한다
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
}
}
}
return dp[n][amt];
}
/* 동전 교환 II: 공간을 최적화한 동적 계획법 */
function coinChangeIIDPComp(coins, amt) {
const n = coins.length;
// dp 테이블을 초기화한다
const dp = Array.from({ length: amt + 1 }, () => 0);
dp[0] = 1;
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let a = 1; a <= amt; a++) {
if (coins[i - 1] > a) {
// 목표 금액을 초과하면 동전 i를 선택하지 않는다
dp[a] = dp[a];
} else {
// 동전 i를 선택하지 않는 경우와 선택하는 경우의 방법 수를 더한다
dp[a] = dp[a] + dp[a - coins[i - 1]];
}
}
}
return dp[amt];
}
/* 실행 코드 */
const coins = [1, 2, 5];
const amt = 5;
// 동적 계획법
let res = coinChangeIIDP(coins, amt);
console.log(`목표 금액을 만드는 동전 조합의 수는 ${res}개이다`);
// 공간을 최적화한 동적 계획법
res = coinChangeIIDPComp(coins, amt);
console.log(`목표 금액을 만드는 동전 조합의 수는 ${res}개이다`);

View File

@@ -0,0 +1,135 @@
/**
* File: edit_distance.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 편집 거리: 완전 탐색 */
function editDistanceDFS(s, t, i, j) {
// s와 t가 모두 비어 있으면 0을 반환한다
if (i === 0 && j === 0) return 0;
// s가 비어 있으면 t의 길이를 반환한다
if (i === 0) return j;
// t가 비어 있으면 s의 길이를 반환한다
if (j === 0) return i;
// 두 문자가 같으면 두 문자를 바로 건너뛴다
if (s.charAt(i - 1) === t.charAt(j - 1))
return editDistanceDFS(s, t, i - 1, j - 1);
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
const insert = editDistanceDFS(s, t, i, j - 1);
const del = editDistanceDFS(s, t, i - 1, j);
const replace = editDistanceDFS(s, t, i - 1, j - 1);
// 최소 편집 횟수를 반환한다
return Math.min(insert, del, replace) + 1;
}
/* 편집 거리: 메모이제이션을 이용한 탐색 */
function editDistanceDFSMem(s, t, mem, i, j) {
// s와 t가 모두 비어 있으면 0을 반환한다
if (i === 0 && j === 0) return 0;
// s가 비어 있으면 t의 길이를 반환한다
if (i === 0) return j;
// t가 비어 있으면 s의 길이를 반환한다
if (j === 0) return i;
// 기록이 이미 있으면 해당 값을 바로 반환한다
if (mem[i][j] !== -1) return mem[i][j];
// 두 문자가 같으면 두 문자를 바로 건너뛴다
if (s.charAt(i - 1) === t.charAt(j - 1))
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
const insert = editDistanceDFSMem(s, t, mem, i, j - 1);
const del = editDistanceDFSMem(s, t, mem, i - 1, j);
const replace = editDistanceDFSMem(s, t, mem, i - 1, j - 1);
// 최소 편집 횟수를 기록하고 반환한다
mem[i][j] = Math.min(insert, del, replace) + 1;
return mem[i][j];
}
/* 편집 거리: 동적 계획법 */
function editDistanceDP(s, t) {
const n = s.length,
m = t.length;
const dp = Array.from({ length: n + 1 }, () => new Array(m + 1).fill(0));
// 상태 전이: 첫 번째 행과 첫 번째 열
for (let i = 1; i <= n; i++) {
dp[i][0] = i;
}
for (let j = 1; j <= m; j++) {
dp[0][j] = j;
}
// 상태 전이: 나머지 행과 열
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= m; j++) {
if (s.charAt(i - 1) === t.charAt(j - 1)) {
// 두 문자가 같으면 두 문자를 바로 건너뛴다
dp[i][j] = dp[i - 1][j - 1];
} else {
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
dp[i][j] =
Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
}
}
}
return dp[n][m];
}
/* 편집 거리: 공간을 최적화한 동적 계획법 */
function editDistanceDPComp(s, t) {
const n = s.length,
m = t.length;
const dp = new Array(m + 1).fill(0);
// 상태 전이: 첫 번째 행
for (let j = 1; j <= m; j++) {
dp[j] = j;
}
// 상태 전이: 나머지 행
for (let i = 1; i <= n; i++) {
// 상태 전이: 첫 번째 열
let leftup = dp[0]; // dp[i-1, j-1]을 임시로 저장한다
dp[0] = i;
// 상태 전이: 나머지 열
for (let j = 1; j <= m; j++) {
const temp = dp[j];
if (s.charAt(i - 1) === t.charAt(j - 1)) {
// 두 문자가 같으면 두 문자를 바로 건너뛴다
dp[j] = leftup;
} else {
// 최소 편집 횟수 = 삽입, 삭제, 교체 세 연산에 대한 최소 편집 횟수 + 1
dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
}
leftup = temp; // 다음 반복의 dp[i-1, j-1]로 갱신한다
}
}
return dp[m];
}
const s = 'bag';
const t = 'pack';
const n = s.length,
m = t.length;
// 완전 탐색
let res = editDistanceDFS(s, t, n, m);
console.log(`${s} → ${t} 변경에 필요한 최소 편집 횟수: ${res}`);
// 메모이제이션을 이용한 탐색
const mem = Array.from(new Array(n + 1), () => new Array(m + 1).fill(-1));
res = editDistanceDFSMem(s, t, mem, n, m);
console.log(`${s} → ${t} 변경에 필요한 최소 편집 횟수: ${res}`);
// 동적 계획법
res = editDistanceDP(s, t);
console.log(`${s} → ${t} 변경에 필요한 최소 편집 횟수: ${res}`);
// 공간을 최적화한 동적 계획법
res = editDistanceDPComp(s, t);
console.log(`${s} → ${t} 변경에 필요한 최소 편집 횟수: ${res}`);

View File

@@ -0,0 +1,113 @@
/**
* File: knapsack.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 0-1 배낭: 완전 탐색 */
function knapsackDFS(wgt, val, i, c) {
// 모든 물건의 선택을 마쳤거나 배낭에 남은 용량이 없으면 가치 0을 반환한다
if (i === 0 || c === 0) {
return 0;
}
// 배낭 용량을 초과하면 배낭에 넣지 않는 선택만 가능하다
if (wgt[i - 1] > c) {
return knapsackDFS(wgt, val, i - 1, c);
}
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
const no = knapsackDFS(wgt, val, i - 1, c);
const yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
// 두 경우 중 더 큰 가치를 반환한다
return Math.max(no, yes);
}
/* 0-1 배낭: 메모이제이션을 이용한 탐색 */
function knapsackDFSMem(wgt, val, mem, i, c) {
// 모든 물건의 선택을 마쳤거나 배낭에 남은 용량이 없으면 가치 0을 반환한다
if (i === 0 || c === 0) {
return 0;
}
// 기록이 이미 있으면 바로 반환한다
if (mem[i][c] !== -1) {
return mem[i][c];
}
// 배낭 용량을 초과하면 배낭에 넣지 않는 선택만 가능하다
if (wgt[i - 1] > c) {
return knapsackDFSMem(wgt, val, mem, i - 1, c);
}
// 물건 i를 넣지 않는 경우와 넣는 경우의 최대 가치를 계산한다
const no = knapsackDFSMem(wgt, val, mem, i - 1, c);
const yes =
knapsackDFSMem(wgt, val, mem, i - 1, c - wgt[i - 1]) + val[i - 1];
// 두 경우 중 더 큰 가치를 기록하고 반환한다
mem[i][c] = Math.max(no, yes);
return mem[i][c];
}
/* 0-1 배낭: 동적 계획법 */
function knapsackDP(wgt, val, cap) {
const n = wgt.length;
// dp 테이블을 초기화한다
const dp = Array(n + 1)
.fill(0)
.map(() => Array(cap + 1).fill(0));
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[i][c] = dp[i - 1][c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[i][c] = Math.max(
dp[i - 1][c],
dp[i - 1][c - wgt[i - 1]] + val[i - 1]
);
}
}
}
return dp[n][cap];
}
/* 0-1 배낭: 공간을 최적화한 동적 계획법 */
function knapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// dp 테이블을 초기화한다
const dp = Array(cap + 1).fill(0);
// 상태 전이
for (let i = 1; i <= n; i++) {
// 역방향 순회
for (let c = cap; c >= 1; c--) {
if (wgt[i - 1] <= c) {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* 실행 코드 */
const wgt = [10, 20, 30, 40, 50];
const val = [50, 120, 150, 210, 240];
const cap = 50;
const n = wgt.length;
// 완전 탐색
let res = knapsackDFS(wgt, val, n, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);
// 메모이제이션을 이용한 탐색
const mem = Array.from({ length: n + 1 }, () =>
Array.from({ length: cap + 1 }, () => -1)
);
res = knapsackDFSMem(wgt, val, mem, n, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);
// 동적 계획법
res = knapsackDP(wgt, val, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);
// 공간을 최적화한 동적 계획법
res = knapsackDPComp(wgt, val, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);

View File

@@ -0,0 +1,49 @@
/**
* File: min_cost_climbing_stairs_dp.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 계단 오르기의 최소 비용: 동적 계획법 */
function minCostClimbingStairsDP(cost) {
const n = cost.length - 1;
if (n === 1 || n === 2) {
return cost[n];
}
// 부분 문제의 해를 저장할 dp 테이블을 초기화한다
const dp = new Array(n + 1);
// 초기 상태: 가장 작은 부분 문제의 해를 미리 설정한다
dp[1] = cost[1];
dp[2] = cost[2];
// 상태 전이: 작은 부분 문제부터 점차 큰 부분 문제를 푼다
for (let i = 3; i <= n; i++) {
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
}
return dp[n];
}
/* 계단 오르기의 최소 비용: 공간을 최적화한 동적 계획법 */
function minCostClimbingStairsDPComp(cost) {
const n = cost.length - 1;
if (n === 1 || n === 2) {
return cost[n];
}
let a = cost[1],
b = cost[2];
for (let i = 3; i <= n; i++) {
const tmp = b;
b = Math.min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
/* 실행 코드 */
const cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
console.log('입력한 계단의 비용 리스트:', cost);
let res = minCostClimbingStairsDP(cost);
console.log(`계단을 모두 오르는 최소 비용: ${res}`);
res = minCostClimbingStairsDPComp(cost);
console.log(`계단을 모두 오르는 최소 비용: ${res}`);

View File

@@ -0,0 +1,121 @@
/**
* File: min_path_sum.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 최소 경로 합: 완전 탐색 */
function minPathSumDFS(grid, i, j) {
// 왼쪽 위 모서리의 칸이면 탐색을 종료한다
if (i === 0 && j === 0) {
return grid[0][0];
}
// 행 또는 열 인덱스가 범위를 벗어나면 비용 +∞를 반환한다
if (i < 0 || j < 0) {
return Infinity;
}
// 왼쪽 위 모서리에서 (i-1, j)와 (i, j-1)까지의 최소 경로 비용을 계산한다
const up = minPathSumDFS(grid, i - 1, j);
const left = minPathSumDFS(grid, i, j - 1);
// 왼쪽 위 모서리에서 (i, j)까지의 최소 경로 비용을 반환한다
return Math.min(left, up) + grid[i][j];
}
/* 최소 경로 합: 메모이제이션을 이용한 탐색 */
function minPathSumDFSMem(grid, mem, i, j) {
// 왼쪽 위 모서리의 칸이면 탐색을 종료한다
if (i === 0 && j === 0) {
return grid[0][0];
}
// 행 또는 열 인덱스가 범위를 벗어나면 비용 +∞를 반환한다
if (i < 0 || j < 0) {
return Infinity;
}
// 기록이 이미 있으면 바로 반환한다
if (mem[i][j] !== -1) {
return mem[i][j];
}
// 왼쪽 칸과 위쪽 칸까지의 최소 경로 비용
const up = minPathSumDFSMem(grid, mem, i - 1, j);
const left = minPathSumDFSMem(grid, mem, i, j - 1);
// 왼쪽 위 모서리에서 (i, j)까지의 최소 경로 비용을 기록하고 반환한다
mem[i][j] = Math.min(left, up) + grid[i][j];
return mem[i][j];
}
/* 최소 경로 합: 동적 계획법 */
function minPathSumDP(grid) {
const n = grid.length,
m = grid[0].length;
// dp 테이블을 초기화한다
const dp = Array.from({ length: n }, () =>
Array.from({ length: m }, () => 0)
);
dp[0][0] = grid[0][0];
// 상태 전이: 첫 번째 행
for (let j = 1; j < m; j++) {
dp[0][j] = dp[0][j - 1] + grid[0][j];
}
// 상태 전이: 첫 번째 열
for (let i = 1; i < n; i++) {
dp[i][0] = dp[i - 1][0] + grid[i][0];
}
// 상태 전이: 나머지 행과 열
for (let i = 1; i < n; i++) {
for (let j = 1; j < m; j++) {
dp[i][j] = Math.min(dp[i][j - 1], dp[i - 1][j]) + grid[i][j];
}
}
return dp[n - 1][m - 1];
}
/* 최소 경로 합: 공간을 최적화한 동적 계획법 */
function minPathSumDPComp(grid) {
const n = grid.length,
m = grid[0].length;
// dp 테이블을 초기화한다
const dp = new Array(m);
// 상태 전이: 첫 번째 행
dp[0] = grid[0][0];
for (let j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// 상태 전이: 나머지 행
for (let i = 1; i < n; i++) {
// 상태 전이: 첫 번째 열
dp[0] = dp[0] + grid[i][0];
// 상태 전이: 나머지 열
for (let j = 1; j < m; j++) {
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
/* 실행 코드 */
const grid = [
[1, 3, 1, 5],
[2, 2, 4, 2],
[5, 3, 2, 1],
[4, 3, 5, 2],
];
const n = grid.length,
m = grid[0].length;
// 완전 탐색
let res = minPathSumDFS(grid, n - 1, m - 1);
console.log(`왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: ${res}`);
// 메모이제이션을 이용한 탐색
const mem = Array.from({ length: n }, () =>
Array.from({ length: m }, () => -1)
);
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
console.log(`왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: ${res}`);
// 동적 계획법
res = minPathSumDP(grid);
console.log(`왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: ${res}`);
// 공간을 최적화한 동적 계획법
res = minPathSumDPComp(grid);
console.log(`왼쪽 위에서 오른쪽 아래까지의 최소 경로 합: ${res}`);

View File

@@ -0,0 +1,63 @@
/**
* File: unbounded_knapsack.js
* Created Time: 2023-08-23
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 무한 배낭: 동적 계획법 */
function unboundedKnapsackDP(wgt, val, cap) {
const n = wgt.length;
// dp 테이블을 초기화한다
const dp = Array.from({ length: n + 1 }, () =>
Array.from({ length: cap + 1 }, () => 0)
);
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[i][c] = dp[i - 1][c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[i][c] = Math.max(
dp[i - 1][c],
dp[i][c - wgt[i - 1]] + val[i - 1]
);
}
}
}
return dp[n][cap];
}
/* 무한 배낭: 공간을 최적화한 동적 계획법 */
function unboundedKnapsackDPComp(wgt, val, cap) {
const n = wgt.length;
// dp 테이블을 초기화한다
const dp = Array.from({ length: cap + 1 }, () => 0);
// 상태 전이
for (let i = 1; i <= n; i++) {
for (let c = 1; c <= cap; c++) {
if (wgt[i - 1] > c) {
// 배낭 용량을 초과하면 물건 i를 선택하지 않는다
dp[c] = dp[c];
} else {
// 물건 i를 선택하지 않는 경우와 선택하는 경우 중 더 큰 값
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
/* 실행 코드 */
const wgt = [1, 2, 3];
const val = [5, 11, 15];
const cap = 4;
// 동적 계획법
let res = unboundedKnapsackDP(wgt, val, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);
// 공간을 최적화한 동적 계획법
res = unboundedKnapsackDPComp(wgt, val, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);

View File

@@ -0,0 +1,142 @@
/**
* File: graph_adjacency_list.js
* Created Time: 2023-02-09
* Author: Justin (xiefahit@gmail.com)
*/
const { Vertex } = require('../modules/Vertex');
/* 인접 리스트로 구현한 무방향 그래프 클래스 */
class GraphAdjList {
// 인접 리스트의 key: 정점, value: 해당 정점의 모든 인접 정점
adjList;
/* 생성자 */
constructor(edges) {
this.adjList = new Map();
// 모든 정점과 간선을 추가한다
for (const edge of edges) {
this.addVertex(edge[0]);
this.addVertex(edge[1]);
this.addEdge(edge[0], edge[1]);
}
}
/* 정점 개수 반환 */
size() {
return this.adjList.size;
}
/* 간선 추가 */
addEdge(vet1, vet2) {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2
) {
throw new Error('잘못된 인수');
}
// 간선 vet1 - vet2를 추가한다
this.adjList.get(vet1).push(vet2);
this.adjList.get(vet2).push(vet1);
}
/* 간선 삭제 */
removeEdge(vet1, vet2) {
if (
!this.adjList.has(vet1) ||
!this.adjList.has(vet2) ||
vet1 === vet2 ||
this.adjList.get(vet1).indexOf(vet2) === -1
) {
throw new Error('잘못된 인수');
}
// 간선 vet1 - vet2를 삭제한다
this.adjList.get(vet1).splice(this.adjList.get(vet1).indexOf(vet2), 1);
this.adjList.get(vet2).splice(this.adjList.get(vet2).indexOf(vet1), 1);
}
/* 정점 추가 */
addVertex(vet) {
if (this.adjList.has(vet)) return;
// 인접 리스트에 새 연결 리스트를 추가한다
this.adjList.set(vet, []);
}
/* 정점 삭제 */
removeVertex(vet) {
if (!this.adjList.has(vet)) {
throw new Error('잘못된 인수');
}
// 인접 리스트에서 정점 vet에 해당하는 연결 리스트를 삭제한다
this.adjList.delete(vet);
// 다른 정점의 연결 리스트를 순회하여 vet를 포함하는 모든 간선을 삭제한다
for (const set of this.adjList.values()) {
const index = set.indexOf(vet);
if (index > -1) {
set.splice(index, 1);
}
}
}
/* 인접 리스트 출력 */
print() {
console.log('인접 리스트 =');
for (const [key, value] of this.adjList) {
const tmp = [];
for (const vertex of value) {
tmp.push(vertex.val);
}
console.log(key.val + ': ' + tmp.join());
}
}
}
if (require.main === module) {
/* 실행 코드 */
/* 무방향 그래프 초기화 */
const v0 = new Vertex(1),
v1 = new Vertex(3),
v2 = new Vertex(2),
v3 = new Vertex(5),
v4 = new Vertex(4);
const edges = [
[v0, v1],
[v1, v2],
[v2, v3],
[v0, v3],
[v2, v4],
[v3, v4],
];
const graph = new GraphAdjList(edges);
console.log('\n초기화한 후의 그래프');
graph.print();
/* 간선 추가 */
// 정점 1, 2는 각각 v0, v2이다
graph.addEdge(v0, v2);
console.log('\n간선 1-2를 추가한 후의 그래프');
graph.print();
/* 간선 삭제 */
// 정점 1, 3은 각각 v0, v1이다
graph.removeEdge(v0, v1);
console.log('\n간선 1-3을 삭제한 후의 그래프');
graph.print();
/* 정점 추가 */
const v5 = new Vertex(6);
graph.addVertex(v5);
console.log('\n정점 6을 추가한 후의 그래프');
graph.print();
/* 정점 삭제 */
// 정점 3은 v1이다
graph.removeVertex(v1);
console.log('\n정점 3을 삭제한 후의 그래프');
graph.print();
}
module.exports = {
GraphAdjList,
};

View File

@@ -0,0 +1,132 @@
/**
* File: graph_adjacency_matrix.js
* Created Time: 2023-02-09
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
/* 인접 행렬로 구현한 무방향 그래프 클래스 */
class GraphAdjMat {
vertices; // 정점 리스트의 원소는 정점 값을, 인덱스는 정점 인덱스를 나타낸다
adjMat; // 인접 행렬의 행과 열 인덱스는 정점 인덱스에 해당한다
/* 생성자 */
constructor(vertices, edges) {
this.vertices = [];
this.adjMat = [];
// 정점 추가
for (const val of vertices) {
this.addVertex(val);
}
// 간선 추가
// edges의 원소는 정점 인덱스, 즉 vertices 원소의 인덱스를 나타낸다
for (const e of edges) {
this.addEdge(e[0], e[1]);
}
}
/* 정점 개수 반환 */
size() {
return this.vertices.length;
}
/* 정점 추가 */
addVertex(val) {
const n = this.size();
// 정점 리스트에 새 정점의 값을 추가한다
this.vertices.push(val);
// 인접 행렬에 행 하나를 추가한다
const newRow = [];
for (let j = 0; j < n; j++) {
newRow.push(0);
}
this.adjMat.push(newRow);
// 인접 행렬에 열 하나를 추가한다
for (const row of this.adjMat) {
row.push(0);
}
}
/* 정점 삭제 */
removeVertex(index) {
if (index >= this.size()) {
throw new RangeError('인덱스가 범위를 벗어났다');
}
// 정점 리스트에서 인덱스 index의 정점을 제거한다
this.vertices.splice(index, 1);
// 인접 행렬에서 인덱스 index의 행을 삭제한다
this.adjMat.splice(index, 1);
// 인접 행렬에서 인덱스 index의 열을 삭제한다
for (const row of this.adjMat) {
row.splice(index, 1);
}
}
/* 간선 추가 */
// 매개변수 i, j는 vertices 원소의 인덱스에 해당한다
addEdge(i, j) {
// 인덱스가 범위를 벗어나거나 서로 같은 경우를 처리한다
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('인덱스가 범위를 벗어났다');
}
// 무방향 그래프의 인접 행렬은 주대각선을 기준으로 대칭이므로 (i, j) === (j, i)를 만족한다
this.adjMat[i][j] = 1;
this.adjMat[j][i] = 1;
}
/* 간선 삭제 */
// 매개변수 i, j는 vertices 원소의 인덱스에 해당한다
removeEdge(i, j) {
// 인덱스가 범위를 벗어나거나 서로 같은 경우를 처리한다
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
throw new RangeError('인덱스가 범위를 벗어났다');
}
this.adjMat[i][j] = 0;
this.adjMat[j][i] = 0;
}
/* 인접 행렬 출력 */
print() {
console.log('정점 리스트 = ', this.vertices);
console.log('인접 행렬 =', this.adjMat);
}
}
/* 실행 코드 */
/* 무방향 그래프 초기화 */
// edges의 원소는 정점 인덱스, 즉 vertices 원소의 인덱스를 나타낸다
const vertices = [1, 3, 2, 5, 4];
const edges = [
[0, 1],
[1, 2],
[2, 3],
[0, 3],
[2, 4],
[3, 4],
];
const graph = new GraphAdjMat(vertices, edges);
console.log('\n초기화한 후의 그래프');
graph.print();
/* 간선 추가 */
// 정점 1, 2의 인덱스는 각각 0, 2이다
graph.addEdge(0, 2);
console.log('\n간선 1-2를 추가한 후의 그래프');
graph.print();
/* 간선 삭제 */
// 정점 1, 3의 인덱스는 각각 0, 1이다
graph.removeEdge(0, 1);
console.log('\n간선 1-3을 삭제한 후의 그래프');
graph.print();
/* 정점 추가 */
graph.addVertex(6);
console.log('\n정점 6을 추가한 후의 그래프');
graph.print();
/* 정점 삭제 */
// 정점 3의 인덱스는 1이다
graph.removeVertex(1);
console.log('\n정점 3을 삭제한 후의 그래프');
graph.print();

View File

@@ -0,0 +1,61 @@
/**
* File: graph_bfs.js
* Created Time: 2023-02-21
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
const { GraphAdjList } = require('./graph_adjacency_list');
const { Vertex } = require('../modules/Vertex');
/* 너비 우선 순회 */
// 지정한 정점의 모든 인접 정점을 얻기 쉽도록 그래프를 인접 리스트로 표현한다
function graphBFS(graph, startVet) {
// 정점 순회 순서
const res = [];
// 방문한 정점을 기록하는 해시 집합
const visited = new Set();
visited.add(startVet);
// 큐를 사용하여 BFS를 구현한다
const que = [startVet];
// 정점 vet에서 시작하여 모든 정점을 방문할 때까지 반복한다
while (que.length) {
const vet = que.shift(); // 큐 맨 앞의 정점을 꺼낸다
res.push(vet); // 방문한 정점을 기록한다
// 해당 정점의 모든 인접 정점을 순회한다
for (const adjVet of graph.adjList.get(vet) ?? []) {
if (visited.has(adjVet)) {
continue; // 이미 방문한 정점은 건너뛴다
}
que.push(adjVet); // 방문하지 않은 정점만 큐에 삽입한다
visited.add(adjVet); // 해당 정점을 방문했다고 표시한다
}
}
// 정점 순회 순서를 반환한다
return res;
}
/* 실행 코드 */
/* 무방향 그래프 초기화 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
const edges = [
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[1], v[4]],
[v[2], v[5]],
[v[3], v[4]],
[v[3], v[6]],
[v[4], v[5]],
[v[4], v[7]],
[v[5], v[8]],
[v[6], v[7]],
[v[7], v[8]],
];
const graph = new GraphAdjList(edges);
console.log('\n초기화한 후의 그래프');
graph.print();
/* 너비 우선 순회 */
const res = graphBFS(graph, v[0]);
console.log('\n너비 우선 순회(BFS)의 정점 순서');
console.log(Vertex.vetsToVals(res));

View File

@@ -0,0 +1,54 @@
/**
* File: graph_dfs.js
* Created Time: 2023-02-21
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
const { Vertex } = require('../modules/Vertex');
const { GraphAdjList } = require('./graph_adjacency_list');
/* 깊이 우선 순회 */
// 지정한 정점의 모든 인접 정점을 얻기 쉽도록 그래프를 인접 리스트로 표현한다
function dfs(graph, visited, res, vet) {
res.push(vet); // 방문한 정점을 기록한다
visited.add(vet); // 해당 정점을 방문했다고 표시한다
// 해당 정점의 모든 인접 정점을 순회한다
for (const adjVet of graph.adjList.get(vet)) {
if (visited.has(adjVet)) {
continue; // 이미 방문한 정점은 건너뛴다
}
// 인접 정점을 재귀적으로 방문한다
dfs(graph, visited, res, adjVet);
}
}
/* 깊이 우선 순회 */
// 지정한 정점의 모든 인접 정점을 얻기 쉽도록 그래프를 인접 리스트로 표현한다
function graphDFS(graph, startVet) {
// 정점 순회 순서
const res = [];
// 방문한 정점을 기록하는 해시 집합
const visited = new Set();
dfs(graph, visited, res, startVet);
return res;
}
/* 실행 코드 */
/* 무방향 그래프 초기화 */
const v = Vertex.valsToVets([0, 1, 2, 3, 4, 5, 6]);
const edges = [
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[2], v[5]],
[v[4], v[5]],
[v[5], v[6]],
];
const graph = new GraphAdjList(edges);
console.log('\n초기화한 후의 그래프');
graph.print();
/* 깊이 우선 순회 */
const res = graphDFS(graph, v[0]);
console.log('\n깊이 우선 순회(DFS)의 정점 순서');
console.log(Vertex.vetsToVals(res));

View File

@@ -0,0 +1,48 @@
/**
* File: coin_change_greedy.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* 동전 교환: 탐욕 */
function coinChangeGreedy(coins, amt) {
// coins 배열이 정렬되어 있다고 가정한다
let i = coins.length - 1;
let count = 0;
// 남은 금액이 없을 때까지 탐욕적 선택을 반복한다
while (amt > 0) {
// 남은 금액보다 작으면서 가장 가까운 금액의 동전을 찾는다
while (i > 0 && coins[i] > amt) {
i--;
}
// coins[i]를 선택한다
amt -= coins[i];
count++;
}
// 가능한 방법을 찾지 못하면 -1을 반환한다
return amt === 0 ? count : -1;
}
/* 실행 코드 */
// 탐욕: 전역 최적해를 찾는 것이 보장된다
let coins = [1, 5, 10, 20, 50, 100];
let amt = 186;
let res = coinChangeGreedy(coins, amt);
console.log(`\ncoins = ${coins}, amt = ${amt}`);
console.log(`목표 금액 ${amt}에 필요한 최소 동전 개수는 ${res}개이다`);
// 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
coins = [1, 20, 50];
amt = 60;
res = coinChangeGreedy(coins, amt);
console.log(`\ncoins = ${coins}, amt = ${amt}`);
console.log(`목표 금액 ${amt}에 필요한 최소 동전 개수는 ${res}개이다`);
console.log('실제로 필요한 최소 개수는 3개이며, 20 + 20 + 20이다');
// 탐욕: 전역 최적해를 찾는 것이 보장되지 않는다
coins = [1, 49, 50];
amt = 98;
res = coinChangeGreedy(coins, amt);
console.log(`\ncoins = ${coins}, amt = ${amt}`);
console.log(`목표 금액 ${amt}에 필요한 최소 동전 개수는 ${res}개이다`);
console.log('실제로 필요한 최소 개수는 2개이며, 49 + 49이다');

View File

@@ -0,0 +1,46 @@
/**
* File: fractional_knapsack.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* 물건 */
class Item {
constructor(w, v) {
this.w = w; // 물건의 무게
this.v = v; // 물건의 가치
}
}
/* 분할 가능한 배낭: 탐욕 */
function fractionalKnapsack(wgt, val, cap) {
// 무게와 가치 두 속성을 갖는 물건의 리스트를 생성한다
const items = wgt.map((w, i) => new Item(w, val[i]));
// 단위 가치 item.v / item.w를 기준으로 내림차순 정렬한다
items.sort((a, b) => b.v / b.w - a.v / a.w);
// 탐욕적 선택을 반복한다
let res = 0;
for (const item of items) {
if (item.w <= cap) {
// 남은 용량이 충분하면 현재 물건을 통째로 배낭에 넣는다
res += item.v;
cap -= item.w;
} else {
// 남은 용량이 부족하면 현재 물건의 일부를 배낭에 넣는다
res += (item.v / item.w) * cap;
// 남은 용량이 없으므로 반복문을 종료한다
break;
}
}
return res;
}
/* 실행 코드 */
const wgt = [10, 20, 30, 40, 50];
const val = [50, 120, 150, 210, 240];
const cap = 50;
const n = wgt.length;
// 탐욕 알고리즘
const res = fractionalKnapsack(wgt, val, cap);
console.log(`배낭 용량을 초과하지 않는 물건의 최대 가치는 ${res}이다`);

View File

@@ -0,0 +1,34 @@
/**
* File: max_capacity.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* 최대 용량: 탐욕 */
function maxCapacity(ht) {
// i와 j가 각각 배열의 양 끝을 가리키도록 초기화한다
let i = 0,
j = ht.length - 1;
// 최대 용량의 초깃값은 0이다
let res = 0;
// 두 칸막이가 만날 때까지 탐욕적 선택을 반복한다
while (i < j) {
// 최대 용량을 갱신한다
const cap = Math.min(ht[i], ht[j]) * (j - i);
res = Math.max(res, cap);
// 낮은 칸막이를 안쪽으로 이동한다
if (ht[i] < ht[j]) {
i += 1;
} else {
j -= 1;
}
}
return res;
}
/* 실행 코드 */
const ht = [3, 8, 5, 2, 7, 7, 3, 4];
// 탐욕 알고리즘
const res = maxCapacity(ht);
console.log(`최대 용량은 ${res}이다`);

View File

@@ -0,0 +1,33 @@
/**
* File: max_product_cutting.js
* Created Time: 2023-09-02
* Author: Justin (xiefahit@gmail.com)
*/
/* 분할 후의 최대 곱: 탐욕 */
function maxProductCutting(n) {
// n <= 3이면 반드시 1 하나가 나오도록 분할해야 한다
if (n <= 3) {
return 1 * (n - 1);
}
// 탐욕적으로 3을 떼어 낸다. a는 3의 개수이고 b는 나머지이다
let a = Math.floor(n / 3);
let b = n % 3;
if (b === 1) {
// 나머지가 1이면 1 * 3 한 쌍을 2 * 2로 바꾼다
return Math.pow(3, a - 1) * 2 * 2;
}
if (b === 2) {
// 나머지가 2이면 별도로 처리하지 않는다
return Math.pow(3, a) * 2;
}
// 나머지가 0이면 별도로 처리하지 않는다
return Math.pow(3, a);
}
/* 실행 코드 */
let n = 58;
// 탐욕 알고리즘
let res = maxProductCutting(n);
console.log(`나눈 조각 길이의 최대 곱은 ${res}이다`);

View File

@@ -0,0 +1,128 @@
/**
* File: array_hash_map.js
* Created Time: 2022-12-26
* Author: Justin (xiefahit@gmail.com)
*/
/* 키-값 쌍 Number -> String */
class Pair {
constructor(key, val) {
this.key = key;
this.val = val;
}
}
/* 배열로 구현한 해시 테이블 */
class ArrayHashMap {
#buckets;
constructor() {
// 버킷 100개를 포함하는 배열을 초기화한다
this.#buckets = new Array(100).fill(null);
}
/* 해시 함수 */
#hashFunc(key) {
return key % 100;
}
/* 조회 연산 */
get(key) {
let index = this.#hashFunc(key);
let pair = this.#buckets[index];
if (pair === null) return null;
return pair.val;
}
/* 추가 연산 */
set(key, val) {
let index = this.#hashFunc(key);
this.#buckets[index] = new Pair(key, val);
}
/* 삭제 연산 */
delete(key) {
let index = this.#hashFunc(key);
// null로 설정하여 삭제를 나타낸다
this.#buckets[index] = null;
}
/* 모든 키-값 쌍 반환 */
entries() {
let arr = [];
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i]);
}
}
return arr;
}
/* 모든 키 반환 */
keys() {
let arr = [];
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i].key);
}
}
return arr;
}
/* 모든 값 반환 */
values() {
let arr = [];
for (let i = 0; i < this.#buckets.length; i++) {
if (this.#buckets[i]) {
arr.push(this.#buckets[i].val);
}
}
return arr;
}
/* 해시 테이블 출력 */
print() {
let pairSet = this.entries();
for (const pair of pairSet) {
console.info(`${pair.key} -> ${pair.val}`);
}
}
}
/* 실행 코드 */
/* 해시 테이블 초기화 */
const map = new ArrayHashMap();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.set(12836, '小哈');
map.set(15937, '小啰');
map.set(16750, '小算');
map.set(13276, '小法');
map.set(10583, '小鸭');
console.info('\n추가를 마친 후의 해시 테이블\n키 -> 값');
map.print();
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
let name = map.get(15937);
console.info('\n학번 15937을 입력하여 조회한 이름 ' + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.delete(10583);
console.info('\n10583을 삭제한 후의 해시 테이블\n키 -> 값');
map.print();
/* 해시 테이블 순회 */
console.info('\n키-값 쌍(키->값) 순회');
for (const pair of map.entries()) {
if (!pair) continue;
console.info(pair.key + ' -> ' + pair.val);
}
console.info('\n키 Key만 순회');
for (const key of map.keys()) {
console.info(key);
}
console.info('\n값 Value만 순회');
for (const val of map.values()) {
console.info(val);
}

View File

@@ -0,0 +1,44 @@
/**
* File: hash_map.js
* Created Time: 2022-12-26
* Author: Justin (xiefahit@gmail.com)
*/
/* 실행 코드 */
/* 해시 테이블 초기화 */
const map = new Map();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.set(12836, '小哈');
map.set(15937, '小啰');
map.set(16750, '小算');
map.set(13276, '小法');
map.set(10583, '小鸭');
console.info('\n추가를 마친 후의 해시 테이블\n키 -> 값');
console.info(map);
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
let name = map.get(15937);
console.info('\n학번 15937을 입력하여 조회한 이름 ' + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.delete(10583);
console.info('\n10583을 삭제한 후의 해시 테이블\n키 -> 값');
console.info(map);
/* 해시 테이블 순회 */
console.info('\n키-값 쌍(키->값) 순회');
for (const [k, v] of map.entries()) {
console.info(k + ' -> ' + v);
}
console.info('\n키 Key만 순회');
for (const k of map.keys()) {
console.info(k);
}
console.info('\n값 Value만 순회');
for (const v of map.values()) {
console.info(v);
}

View File

@@ -0,0 +1,142 @@
/**
* File: hash_map_chaining.js
* Created Time: 2023-08-06
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 키-값 쌍 Number -> String */
class Pair {
constructor(key, val) {
this.key = key;
this.val = val;
}
}
/* 체이닝 해시 테이블 */
class HashMapChaining {
#size; // 키-값 쌍 개수
#capacity; // 해시 테이블 용량
#loadThres; // 용량 확장을 수행하는 적재율 임계값
#extendRatio; // 용량 확장 배수
#buckets; // 버킷 배열
/* 생성자 */
constructor() {
this.#size = 0;
this.#capacity = 4;
this.#loadThres = 2.0 / 3.0;
this.#extendRatio = 2;
this.#buckets = new Array(this.#capacity).fill(null).map((x) => []);
}
/* 해시 함수 */
#hashFunc(key) {
return key % this.#capacity;
}
/* 적재율 */
#loadFactor() {
return this.#size / this.#capacity;
}
/* 조회 연산 */
get(key) {
const index = this.#hashFunc(key);
const bucket = this.#buckets[index];
// 버킷을 순회하다 key를 찾으면 해당 val을 반환한다
for (const pair of bucket) {
if (pair.key === key) {
return pair.val;
}
}
// key를 찾지 못하면 null을 반환한다
return null;
}
/* 추가 연산 */
put(key, val) {
// 적재율이 임계값을 초과하면 용량을 확장한다
if (this.#loadFactor() > this.#loadThres) {
this.#extend();
}
const index = this.#hashFunc(key);
const bucket = this.#buckets[index];
// 버킷을 순회하다 지정한 key를 만나면 해당 val을 갱신하고 반환한다
for (const pair of bucket) {
if (pair.key === key) {
pair.val = val;
return;
}
}
// 해당 key가 없으면 키-값 쌍을 맨 뒤에 추가한다
const pair = new Pair(key, val);
bucket.push(pair);
this.#size++;
}
/* 삭제 연산 */
remove(key) {
const index = this.#hashFunc(key);
let bucket = this.#buckets[index];
// 버킷을 순회하며 키-값 쌍을 삭제한다
for (let i = 0; i < bucket.length; i++) {
if (bucket[i].key === key) {
bucket.splice(i, 1);
this.#size--;
break;
}
}
}
/* 해시 테이블 용량 확장 */
#extend() {
// 원래 해시 테이블을 임시로 저장한다
const bucketsTmp = this.#buckets;
// 용량을 확장한 새 해시 테이블을 초기화한다
this.#capacity *= this.#extendRatio;
this.#buckets = new Array(this.#capacity).fill(null).map((x) => []);
this.#size = 0;
// 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
for (const bucket of bucketsTmp) {
for (const pair of bucket) {
this.put(pair.key, pair.val);
}
}
}
/* 해시 테이블 출력 */
print() {
for (const bucket of this.#buckets) {
let res = [];
for (const pair of bucket) {
res.push(pair.key + ' -> ' + pair.val);
}
console.log(res);
}
}
}
/* 실행 코드 */
/* 해시 테이블 초기화 */
const map = new HashMapChaining();
/* 추가 연산 */
// 해시 테이블에 (key, value) 키-값 쌍을 추가한다
map.put(12836, '小哈');
map.put(15937, '小啰');
map.put(16750, '小算');
map.put(13276, '小法');
map.put(10583, '小鸭');
console.log('\n추가를 마친 후의 해시 테이블\n키 -> 값');
map.print();
/* 조회 연산 */
// 해시 테이블에 키 key를 입력하여 값 value를 얻는다
const name = map.get(13276);
console.log('\n학번 13276을 입력하여 조회한 이름 ' + name);
/* 삭제 연산 */
// 해시 테이블에서 (key, value) 키-값 쌍을 삭제한다
map.remove(12836);
console.log('\n12836을 삭제한 뒤의 해시 테이블\n키 -> 값');
map.print();

View File

@@ -0,0 +1,177 @@
/**
* File: hashMapOpenAddressing.js
* Created Time: 2023-06-13
* Author: yuan0221 (yl1452491917@gmail.com), krahets (krahets@163.com)
*/
/* 키-값 쌍 Number -> String */
class Pair {
constructor(key, val) {
this.key = key;
this.val = val;
}
}
/* 개방 주소법 해시 테이블 */
class HashMapOpenAddressing {
#size; // 키-값 쌍 개수
#capacity; // 해시 테이블 용량
#loadThres; // 용량 확장을 수행하는 적재율 임계값
#extendRatio; // 용량 확장 배수
#buckets; // 버킷 배열
#TOMBSTONE; // 삭제 표시
/* 생성자 */
constructor() {
this.#size = 0; // 키-값 쌍 개수
this.#capacity = 4; // 해시 테이블 용량
this.#loadThres = 2.0 / 3.0; // 용량 확장을 수행하는 적재율 임계값
this.#extendRatio = 2; // 용량 확장 배수
this.#buckets = Array(this.#capacity).fill(null); // 버킷 배열
this.#TOMBSTONE = new Pair(-1, '-1'); // 삭제 표시
}
/* 해시 함수 */
#hashFunc(key) {
return key % this.#capacity;
}
/* 적재율 */
#loadFactor() {
return this.#size / this.#capacity;
}
/* key에 해당하는 버킷 인덱스 탐색 */
#findBucket(key) {
let index = this.#hashFunc(key);
let firstTombstone = -1;
// 선형 탐사로 탐색하고, 빈 버킷을 만나면 반복문을 종료한다
while (this.#buckets[index] !== null) {
// key를 만나면 해당 버킷 인덱스를 반환한다
if (this.#buckets[index].key === key) {
// 이전에 삭제 표시를 만났으면 키-값 쌍을 그 인덱스로 옮긴다
if (firstTombstone !== -1) {
this.#buckets[firstTombstone] = this.#buckets[index];
this.#buckets[index] = this.#TOMBSTONE;
return firstTombstone; // 옮긴 후의 버킷 인덱스를 반환한다
}
return index; // 버킷 인덱스를 반환한다
}
// 처음 만난 삭제 표시를 기록한다
if (
firstTombstone === -1 &&
this.#buckets[index] === this.#TOMBSTONE
) {
firstTombstone = index;
}
// 버킷 인덱스를 계산하고, 끝을 넘어가면 처음으로 돌아온다
index = (index + 1) % this.#capacity;
}
// key가 없으면 추가할 위치의 인덱스를 반환한다
return firstTombstone === -1 ? index : firstTombstone;
}
/* 조회 연산 */
get(key) {
// key에 해당하는 버킷 인덱스 탐색
const index = this.#findBucket(key);
// 키-값 쌍을 찾으면 해당 val을 반환한다
if (
this.#buckets[index] !== null &&
this.#buckets[index] !== this.#TOMBSTONE
) {
return this.#buckets[index].val;
}
// 키-값 쌍이 없으면 null을 반환한다
return null;
}
/* 추가 연산 */
put(key, val) {
// 적재율이 임계값을 초과하면 용량을 확장한다
if (this.#loadFactor() > this.#loadThres) {
this.#extend();
}
// key에 해당하는 버킷 인덱스 탐색
const index = this.#findBucket(key);
// 키-값 쌍을 찾으면 val을 덮어쓰고 반환한다
if (
this.#buckets[index] !== null &&
this.#buckets[index] !== this.#TOMBSTONE
) {
this.#buckets[index].val = val;
return;
}
// 키-값 쌍이 없으면 해당 키-값 쌍을 추가한다
this.#buckets[index] = new Pair(key, val);
this.#size++;
}
/* 삭제 연산 */
remove(key) {
// key에 해당하는 버킷 인덱스 탐색
const index = this.#findBucket(key);
// 키-값 쌍을 찾으면 삭제 표시로 덮어쓴다
if (
this.#buckets[index] !== null &&
this.#buckets[index] !== this.#TOMBSTONE
) {
this.#buckets[index] = this.#TOMBSTONE;
this.#size--;
}
}
/* 해시 테이블 용량 확장 */
#extend() {
// 원래 해시 테이블을 임시로 저장한다
const bucketsTmp = this.#buckets;
// 용량을 확장한 새 해시 테이블을 초기화한다
this.#capacity *= this.#extendRatio;
this.#buckets = Array(this.#capacity).fill(null);
this.#size = 0;
// 원래 해시 테이블의 키-값 쌍을 새 해시 테이블로 옮긴다
for (const pair of bucketsTmp) {
if (pair !== null && pair !== this.#TOMBSTONE) {
this.put(pair.key, pair.val);
}
}
}
/* 해시 테이블 출력 */
print() {
for (const pair of this.#buckets) {
if (pair === null) {
console.log('null');
} else if (pair === this.#TOMBSTONE) {
console.log('TOMBSTONE');
} else {
console.log(pair.key + ' -> ' + pair.val);
}
}
}
}
/* 실행 코드 */
// 해시 테이블 초기화
const hashmap = new HashMapOpenAddressing();
// 추가 연산
// 해시 테이블에 키-값 쌍 (key, val)을 추가한다
hashmap.put(12836, '小哈');
hashmap.put(15937, '小啰');
hashmap.put(16750, '小算');
hashmap.put(13276, '小法');
hashmap.put(10583, '小鸭');
console.log('\n추가를 마친 후의 해시 테이블\n키 -> 값');
hashmap.print();
// 조회 연산
// 해시 테이블에 키 key를 입력하여 값 val을 얻는다
const name = hashmap.get(13276);
console.log('\n학번 13276을 입력하여 조회한 이름 ' + name);
// 삭제 연산
// 해시 테이블에서 키-값 쌍 (key, val)을 삭제한다
hashmap.remove(16750);
console.log('\n16750을 삭제한 후의 해시 테이블\n키 -> 값');
hashmap.print();

View File

@@ -0,0 +1,60 @@
/**
* File: simple_hash.js
* Created Time: 2023-08-06
* Author: yuan0221 (yl1452491917@gmail.com)
*/
/* 덧셈 해시 */
function addHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = (hash + c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* 곱셈 해시 */
function mulHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = (31 * hash + c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* XOR 해시 */
function xorHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash ^= c.charCodeAt(0);
}
return hash % MODULUS;
}
/* 회전 해시 */
function rotHash(key) {
let hash = 0;
const MODULUS = 1000000007;
for (const c of key) {
hash = ((hash << 4) ^ (hash >> 28) ^ c.charCodeAt(0)) % MODULUS;
}
return hash;
}
/* 실행 코드 */
const key = 'Hello 算法';
let hash = addHash(key);
console.log('덧셈 해시값: ' + hash);
hash = mulHash(key);
console.log('곱셈 해시값: ' + hash);
hash = xorHash(key);
console.log('XOR 해시값: ' + hash);
hash = rotHash(key);
console.log('회전 해시값: ' + hash);

View File

@@ -0,0 +1,158 @@
/**
* File: my_heap.js
* Created Time: 2023-02-06
* Author: what-is-me (whatisme@outlook.jp)
*/
const { printHeap } = require('../modules/PrintUtil');
/* 최대 힙 클래스 */
class MaxHeap {
#maxHeap;
/* 생성자: 빈 힙을 만들거나 입력 리스트로 힙을 구성한다 */
constructor(nums) {
// 리스트 원소를 그대로 힙에 추가한다
this.#maxHeap = nums === undefined ? [] : [...nums];
// 리프 노드를 제외한 모든 노드에 힙 재정렬을 수행한다
for (let i = this.#parent(this.size() - 1); i >= 0; i--) {
this.#siftDown(i);
}
}
/* 왼쪽 자식 노드의 인덱스 반환 */
#left(i) {
return 2 * i + 1;
}
/* 오른쪽 자식 노드의 인덱스 반환 */
#right(i) {
return 2 * i + 2;
}
/* 부모 노드의 인덱스 반환 */
#parent(i) {
return Math.floor((i - 1) / 2); // 나눗셈의 결과를 내림한다
}
/* 원소 교환 */
#swap(i, j) {
const tmp = this.#maxHeap[i];
this.#maxHeap[i] = this.#maxHeap[j];
this.#maxHeap[j] = tmp;
}
/* 힙 크기 반환 */
size() {
return this.#maxHeap.length;
}
/* 힙이 비어 있는지 판단 */
isEmpty() {
return this.size() === 0;
}
/* 힙의 루트 원소 접근 */
peek() {
return this.#maxHeap[0];
}
/* 힙에 원소 삽입 */
push(val) {
// 노드 추가
this.#maxHeap.push(val);
// 아래에서 위로 힙을 재정렬한다
this.#siftUp(this.size() - 1);
}
/* 노드 i에서 시작하여 아래에서 위로 힙 재정렬 */
#siftUp(i) {
while (true) {
// 노드 i의 부모 노드를 구한다
const p = this.#parent(i);
// 루트 노드를 넘어가거나 노드를 수정할 필요가 없으면 힙 재정렬을 마친다
if (p < 0 || this.#maxHeap[i] <= this.#maxHeap[p]) break;
// 두 노드를 교환한다
this.#swap(i, p);
// 위쪽으로 힙 재정렬을 반복한다
i = p;
}
}
/* 힙에서 원소 꺼내기 */
pop() {
// 비어 있는 경우를 처리한다
if (this.isEmpty()) throw new Error('힙이 비어 있다');
// 루트 노드와 가장 오른쪽 리프 노드를 교환한다(첫 원소와 마지막 원소 교환)
this.#swap(0, this.size() - 1);
// 노드 삭제
const val = this.#maxHeap.pop();
// 위에서 아래로 힙을 재정렬한다
this.#siftDown(0);
// 힙의 루트 원소를 반환한다
return val;
}
/* 노드 i에서 시작하여 위에서 아래로 힙 재정렬 */
#siftDown(i) {
while (true) {
// 노드 i, l, r 중 값이 가장 큰 노드를 찾아 ma로 표시한다
const l = this.#left(i),
r = this.#right(i);
let ma = i;
if (l < this.size() && this.#maxHeap[l] > this.#maxHeap[ma]) ma = l;
if (r < this.size() && this.#maxHeap[r] > this.#maxHeap[ma]) ma = r;
// 노드 i의 값이 가장 크거나 인덱스 l, r이 범위를 벗어나면 힙을 더 재정렬할 필요가 없으므로 종료한다
if (ma === i) break;
// 두 노드를 교환한다
this.#swap(i, ma);
// 아래쪽으로 힙 재정렬을 반복한다
i = ma;
}
}
/* 힙 출력(이진 트리) */
print() {
printHeap(this.#maxHeap);
}
/* 힙의 원소를 반환한다 */
getMaxHeap() {
return this.#maxHeap;
}
}
/* 실행 코드 */
if (require.main === module) {
/* 최대 힙 초기화 */
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
console.log('\n리스트를 입력하여 힙을 구성한 후');
maxHeap.print();
/* 힙의 루트 원소 반환 */
let peek = maxHeap.peek();
console.log(`\n힙의 루트 원소: ${peek}`);
/* 힙에 원소 삽입 */
let val = 7;
maxHeap.push(val);
console.log(`\n원소를 힙에 삽입한 후(원소: ${val})`);
maxHeap.print();
/* 힙의 루트 원소 꺼내기 */
peek = maxHeap.pop();
console.log(`\n힙의 루트 원소를 꺼낸 후(원소: ${peek})`);
maxHeap.print();
/* 힙 크기 반환 */
let size = maxHeap.size();
console.log(`\n힙의 원소 개수: ${size}`);
/* 힙이 비어 있는지 판단 */
let isEmpty = maxHeap.isEmpty();
console.log(`\n힙이 비어 있는가: ${isEmpty}`);
}
module.exports = {
MaxHeap,
};

View File

@@ -0,0 +1,58 @@
/**
* File: top_k.js
* Created Time: 2023-08-13
* Author: Justin (xiefahit@gmail.com)
*/
const { MaxHeap } = require('./my_heap');
/* 힙에 원소 삽입 */
function pushMinHeap(maxHeap, val) {
// 원소의 부호를 반전한다
maxHeap.push(-val);
}
/* 힙에서 원소 꺼내기 */
function popMinHeap(maxHeap) {
// 원소의 부호를 반전한다
return -maxHeap.pop();
}
/* 힙의 루트 원소 접근 */
function peekMinHeap(maxHeap) {
// 원소의 부호를 반전한다
return -maxHeap.peek();
}
/* 힙의 원소를 반환한다 */
function getMinHeap(maxHeap) {
// 원소의 부호를 반전한다
return maxHeap.getMaxHeap().map((num) => -num);
}
/* 힙을 이용하여 배열에서 가장 큰 k개 원소 탐색 */
function topKHeap(nums, k) {
// 최소 힙 초기화
// 힙의 모든 원소의 부호를 반전하여 최대 힙으로 최소 힙을 구현한다는 점에 유의한다
const maxHeap = new MaxHeap([]);
// 배열의 앞쪽 k개 원소를 힙에 삽입한다
for (let i = 0; i < k; i++) {
pushMinHeap(maxHeap, nums[i]);
}
// k+1번째 원소부터 힙의 길이를 k로 유지한다
for (let i = k; i < nums.length; i++) {
// 현재 원소가 힙의 루트 원소보다 크면 루트 원소를 꺼내고 현재 원소를 힙에 삽입한다
if (nums[i] > peekMinHeap(maxHeap)) {
popMinHeap(maxHeap);
pushMinHeap(maxHeap, nums[i]);
}
}
// 힙의 원소를 반환한다
return getMinHeap(maxHeap);
}
/* 실행 코드 */
const nums = [1, 7, 6, 3, 2];
const k = 3;
const res = topKHeap(nums, k);
console.log(`가장 큰 원소 ${k}개:`, res);

View File

@@ -0,0 +1,60 @@
/**
* File: binary_search.js
* Created Time: 2022-12-22
* Author: JoseHung (szhong@link.cuhk.edu.hk)
*/
/* 이진 탐색(양 끝을 포함하는 닫힌 구간) */
function binarySearch(nums, target) {
// 닫힌 구간 [0, n-1]을 초기화한다. i와 j는 각각 배열의 첫 원소와 마지막 원소를 가리킨다
let i = 0,
j = nums.length - 1;
// 반복하다 탐색 구간이 비면 종료한다(i > j이면 빈 구간이다)
while (i <= j) {
// 중간 인덱스 m을 계산하며, parseInt()로 소수 부분을 버린다
const m = parseInt(i + (j - i) / 2);
if (nums[m] < target)
// 이 경우 target은 구간 [m+1, j]에 있다
i = m + 1;
else if (nums[m] > target)
// 이 경우 target은 구간 [i, m-1]에 있다
j = m - 1;
else return m; // 목표 원소를 찾았으므로 해당 인덱스를 반환한다
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
/* 이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간) */
function binarySearchLCRO(nums, target) {
// 왼쪽 끝만 포함하는 구간 [0, n)을 초기화한다. i는 배열의 첫 원소를, j는 마지막 원소 바로 다음 위치를 가리킨다
let i = 0,
j = nums.length;
// 반복하다 탐색 구간이 비면 종료한다(i = j이면 빈 구간이다)
while (i < j) {
// 중간 인덱스 m을 계산하며, parseInt()로 소수 부분을 버린다
const m = parseInt(i + (j - i) / 2);
if (nums[m] < target)
// 이 경우 target은 구간 [m+1, j)에 있다
i = m + 1;
else if (nums[m] > target)
// 이 경우 target은 구간 [i, m)에 있다
j = m;
// 목표 원소를 찾았으므로 해당 인덱스를 반환한다
else return m;
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
/* 실행 코드 */
const target = 6;
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
/* 이진 탐색(양 끝을 포함하는 닫힌 구간) */
let index = binarySearch(nums, target);
console.log('목표 원소 6의 인덱스 = ' + index);
/* 이진 탐색(왼쪽 끝은 포함하고 오른쪽 끝은 제외하는 구간) */
index = binarySearchLCRO(nums, target);
console.log('목표 원소 6의 인덱스 = ' + index);

View File

@@ -0,0 +1,45 @@
/**
* File: binary_search_edge.js
* Created Time: 2023-08-22
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
const { binarySearchInsertion } = require('./binary_search_insertion.js');
/* 가장 왼쪽에 있는 target을 이진 탐색 */
function binarySearchLeftEdge(nums, target) {
// target의 삽입 위치를 찾는 것과 같다
const i = binarySearchInsertion(nums, target);
// target을 찾지 못했으므로 -1을 반환한다
if (i === nums.length || nums[i] !== target) {
return -1;
}
// target을 찾았으므로 인덱스 i를 반환한다
return i;
}
/* 가장 오른쪽에 있는 target을 이진 탐색 */
function binarySearchRightEdge(nums, target) {
// 가장 왼쪽에 있는 target + 1을 찾는 문제로 바꾼다
const i = binarySearchInsertion(nums, target + 1);
// j는 가장 오른쪽의 target을 가리키고, i는 target보다 큰 첫 번째 원소를 가리킨다
const j = i - 1;
// target을 찾지 못했으므로 -1을 반환한다
if (j === -1 || nums[j] !== target) {
return -1;
}
// target을 찾았으므로 인덱스 j를 반환한다
return j;
}
/* 실행 코드 */
// 중복 원소를 포함하는 배열
const nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
console.log('\n배열 nums = ' + nums);
// 왼쪽 경계와 오른쪽 경계의 이진 탐색
for (const target of [6, 7]) {
let index = binarySearchLeftEdge(nums, target);
console.log('가장 왼쪽 원소 ' + target + ' ; 인덱스: ' + index);
index = binarySearchRightEdge(nums, target);
console.log('가장 오른쪽 원소 ' + target + ' ; 인덱스: ' + index);
}

View File

@@ -0,0 +1,64 @@
/**
* File: binary_search_insertion.js
* Created Time: 2023-08-22
* Author: Gaofer Chou (gaofer-chou@qq.com)
*/
/* 삽입 위치의 이진 탐색(중복 원소 없음) */
function binarySearchInsertionSimple(nums, target) {
let i = 0,
j = nums.length - 1; // 닫힌 구간 [0, n-1]을 초기화한다
while (i <= j) {
const m = Math.floor(i + (j - i) / 2); // 중간 인덱스 m을 계산하며, Math.floor()로 내림한다
if (nums[m] < target) {
i = m + 1; // target은 구간 [m+1, j]에 있다
} else if (nums[m] > target) {
j = m - 1; // target은 구간 [i, m-1]에 있다
} else {
return m; // target을 찾았으므로 삽입 위치 m을 반환한다
}
}
// target을 찾지 못했으므로 삽입 위치 i를 반환한다
return i;
}
/* 삽입 위치의 이진 탐색(중복 원소 있음) */
function binarySearchInsertion(nums, target) {
let i = 0,
j = nums.length - 1; // 닫힌 구간 [0, n-1]을 초기화한다
while (i <= j) {
const m = Math.floor(i + (j - i) / 2); // 중간 인덱스 m을 계산하며, Math.floor()로 내림한다
if (nums[m] < target) {
i = m + 1; // target은 구간 [m+1, j]에 있다
} else if (nums[m] > target) {
j = m - 1; // target은 구간 [i, m-1]에 있다
} else {
j = m - 1; // target보다 작은 가장 오른쪽 원소는 구간 [i, m-1]에 있다
}
}
// 삽입 위치 i를 반환한다
return i;
}
/* 실행 코드 */
// 중복 원소가 없는 배열
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
console.log('\n배열 nums = ' + nums);
// 삽입 위치의 이진 탐색
for (const target of [6, 9]) {
const index = binarySearchInsertionSimple(nums, target);
console.log('원소 ' + target + ' ; 삽입 위치의 인덱스: ' + index);
}
// 중복 원소를 포함하는 배열
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
console.log('\n배열 nums = ' + nums);
// 삽입 위치의 이진 탐색
for (const target of [2, 6, 20]) {
const index = binarySearchInsertion(nums, target);
console.log('원소 ' + target + ' ; 삽입 위치의 인덱스: ' + index);
}
module.exports = {
binarySearchInsertion,
};

View File

@@ -0,0 +1,45 @@
/**
* File: hashing_search.js
* Created Time: 2022-12-29
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
const { arrToLinkedList } = require('../modules/ListNode');
/* 해시 탐색(배열) */
function hashingSearchArray(map, target) {
// 해시 테이블의 key: 목표 원소, value: 인덱스
// 해시 테이블에 해당 key가 없으면 -1을 반환한다
return map.has(target) ? map.get(target) : -1;
}
/* 해시 탐색(연결 리스트) */
function hashingSearchLinkedList(map, target) {
// 해시 테이블의 key: 목표 노드의 값, value: 노드 객체
// 해시 테이블에 해당 key가 없으면 null을 반환한다
return map.has(target) ? map.get(target) : null;
}
/* 실행 코드 */
const target = 3;
/* 해시 탐색(배열) */
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
// 해시 테이블 초기화
const map = new Map();
for (let i = 0; i < nums.length; i++) {
map.set(nums[i], i); // key: 원소, value: 인덱스
}
const index = hashingSearchArray(map, target);
console.log('목표 원소 3의 인덱스 = ' + index);
/* 해시 탐색(연결 리스트) */
let head = arrToLinkedList(nums);
// 해시 테이블 초기화
const map1 = new Map();
while (head != null) {
map1.set(head.val, head); // key: 노드 값, value: 노드
head = head.next;
}
const node = hashingSearchLinkedList(map1, target);
console.log('목표 노드 값 3에 해당하는 노드 객체', node);

View File

@@ -0,0 +1,47 @@
/**
* File: linear_search.js
* Created Time: 2022-12-22
* Author: JoseHung (szhong@link.cuhk.edu.hk)
*/
const { ListNode, arrToLinkedList } = require('../modules/ListNode');
/* 선형 탐색(배열) */
function linearSearchArray(nums, target) {
// 배열 순회
for (let i = 0; i < nums.length; i++) {
// 목표 원소를 찾았으므로 해당 인덱스를 반환한다
if (nums[i] === target) {
return i;
}
}
// 목표 원소를 찾지 못했으므로 -1을 반환한다
return -1;
}
/* 선형 탐색(연결 리스트)*/
function linearSearchLinkedList(head, target) {
// 연결 리스트 순회
while (head) {
// 목표 노드를 찾았으므로 해당 노드를 반환한다
if (head.val === target) {
return head;
}
head = head.next;
}
// 목표 노드를 찾지 못했으므로 null을 반환한다
return null;
}
/* 실행 코드 */
const target = 3;
/* 배열에서 선형 탐색을 수행한다 */
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
const index = linearSearchArray(nums, target);
console.log('목표 원소 3의 인덱스 = ' + index);
/* 연결 리스트에서 선형 탐색을 수행한다 */
const head = arrToLinkedList(nums);
const node = linearSearchLinkedList(head, target);
console.log('목표 노드 값 3에 해당하는 노드 객체 ', node);

View File

@@ -0,0 +1,46 @@
/**
* File: two_sum.js
* Created Time: 2022-12-15
* Author: gyt95 (gytkwan@gmail.com)
*/
/* 방법 1: 완전 열거 */
function twoSumBruteForce(nums, target) {
const n = nums.length;
// 이중 반복문이며 시간 복잡도는 O(n^2)이다
for (let i = 0; i < n; i++) {
for (let j = i + 1; j < n; j++) {
if (nums[i] + nums[j] === target) {
return [i, j];
}
}
}
return [];
}
/* 방법 2: 보조 해시 테이블 */
function twoSumHashTable(nums, target) {
// 보조 해시 테이블의 공간 복잡도는 O(n)이다
let m = {};
// 단일 반복문이며 시간 복잡도는 O(n)이다
for (let i = 0; i < nums.length; i++) {
if (m[target - nums[i]] !== undefined) {
return [m[target - nums[i]], i];
} else {
m[nums[i]] = i;
}
}
return [];
}
/* 실행 코드 */
// 방법 1
const nums = [2, 7, 11, 15],
target = 13;
let res = twoSumBruteForce(nums, target);
console.log('방법 1 res = ', res);
// 방법 2
res = twoSumHashTable(nums, target);
console.log('방법 2 res = ', res);

View File

@@ -0,0 +1,49 @@
/**
* File: bubble_sort.js
* Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 버블 정렬 */
function bubbleSort(nums) {
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (let i = nums.length - 1; i > 0; i--) {
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
}
}
}
}
/* 버블 정렬(플래그 최적화)*/
function bubbleSortWithFlag(nums) {
// 바깥쪽 반복문: 정렬되지 않은 구간은 [0, i]이다
for (let i = nums.length - 1; i > 0; i--) {
let flag = false; // 플래그를 초기화한다
// 안쪽 반복문: 정렬되지 않은 구간 [0, i]의 최댓값을 교환하여 이 구간의 맨 오른쪽으로 옮긴다
for (let j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// nums[j]와 nums[j + 1]을 교환한다
let tmp = nums[j];
nums[j] = nums[j + 1];
nums[j + 1] = tmp;
flag = true; // 원소가 교환되었음을 기록한다
}
}
if (!flag) break; // 이번 버블 과정에서 원소 교환이 없었으므로 바로 종료한다
}
}
/* 실행 코드 */
const nums = [4, 1, 3, 1, 5, 2];
bubbleSort(nums);
console.log('버블 정렬을 마친 후 nums =', nums);
const nums1 = [4, 1, 3, 1, 5, 2];
bubbleSortWithFlag(nums1);
console.log('버블 정렬을 마친 후 nums =', nums1);

View File

@@ -0,0 +1,39 @@
/**
* File: bucket_sort.js
* Created Time: 2023-04-08
* Author: Justin (xiefahit@gmail.com)
*/
/* 버킷 정렬 */
function bucketSort(nums) {
// 버킷 k = n/2개를 초기화하며, 각 버킷에 원소 2개가 배정될 것으로 예상한다
const k = nums.length / 2;
const buckets = [];
for (let i = 0; i < k; i++) {
buckets.push([]);
}
// 1. 배열 원소를 각 버킷에 배정한다
for (const num of nums) {
// 입력 데이터의 범위는 [0, 1)이며, num * k를 사용하여 인덱스 범위 [0, k-1]에 대응시킨다
const i = Math.floor(num * k);
// num을 버킷 i에 추가한다
buckets[i].push(num);
}
// 2. 각 버킷을 정렬한다
for (const bucket of buckets) {
// 내장 정렬 함수를 사용하며, 다른 정렬 알고리즘으로 대체할 수도 있다
bucket.sort((a, b) => a - b);
}
// 3. 버킷을 순회하여 결과를 합친다
let i = 0;
for (const bucket of buckets) {
for (const num of bucket) {
nums[i++] = num;
}
}
}
/* 실행 코드 */
const nums = [0.49, 0.96, 0.82, 0.09, 0.57, 0.43, 0.91, 0.75, 0.15, 0.37];
bucketSort(nums);
console.log('버킷 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,65 @@
/**
* File: counting_sort.js
* Created Time: 2023-04-08
* Author: Justin (xiefahit@gmail.com)
*/
/* 계수 정렬 */
// 간단한 구현이며, 객체 정렬에는 사용할 수 없다
function countingSortNaive(nums) {
// 1. 배열의 최댓값 m을 구한다
let m = Math.max(...nums);
// 2. 각 숫자의 등장 횟수를 센다
// counter[num]은 num의 등장 횟수를 나타낸다
const counter = new Array(m + 1).fill(0);
for (const num of nums) {
counter[num]++;
}
// 3. counter를 순회하며 각 원소를 원래 배열 nums에 채운다
let i = 0;
for (let num = 0; num < m + 1; num++) {
for (let j = 0; j < counter[num]; j++, i++) {
nums[i] = num;
}
}
}
/* 계수 정렬 */
// 완전한 구현이며, 객체를 정렬할 수 있고 안정 정렬이다
function countingSort(nums) {
// 1. 배열의 최댓값 m을 구한다
let m = Math.max(...nums);
// 2. 각 숫자의 등장 횟수를 센다
// counter[num]은 num의 등장 횟수를 나타낸다
const counter = new Array(m + 1).fill(0);
for (const num of nums) {
counter[num]++;
}
// 3. counter의 접두 합을 구하여 등장 횟수를 마지막 인덱스로 변환한다
// 즉, counter[num]-1은 res에서 num이 마지막으로 등장하는 인덱스이다
for (let i = 0; i < m; i++) {
counter[i + 1] += counter[i];
}
// 4. nums를 역순으로 순회하며 각 원소를 결과 배열 res에 채운다
// 결과를 기록할 배열 res를 초기화한다
const n = nums.length;
const res = new Array(n);
for (let i = n - 1; i >= 0; i--) {
const num = nums[i];
res[counter[num] - 1] = num; // num을 해당 인덱스에 배치한다
counter[num]--; // 접두 합을 1 감소시켜 다음에 num을 배치할 인덱스를 구한다
}
// 결과 배열 res로 원래 배열 nums를 덮어쓴다
for (let i = 0; i < n; i++) {
nums[i] = res[i];
}
}
/* 실행 코드 */
const nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
countingSortNaive(nums);
console.log('계수 정렬(객체 정렬 불가)을 마친 후 nums =', nums);
const nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
countingSort(nums1);
console.log('계수 정렬을 마친 후 nums1 =', nums1);

View File

@@ -0,0 +1,49 @@
/**
* File: heap_sort.js
* Created Time: 2023-06-04
* Author: Justin (xiefahit@gmail.com)
*/
/* 길이가 n인 힙에서 노드 i부터 위에서 아래로 힙 재정렬 */
function siftDown(nums, n, i) {
while (true) {
// 노드 i, l, r 중 값이 가장 큰 노드를 찾아 ma로 표시한다
let l = 2 * i + 1;
let r = 2 * i + 2;
let ma = i;
if (l < n && nums[l] > nums[ma]) {
ma = l;
}
if (r < n && nums[r] > nums[ma]) {
ma = r;
}
// 노드 i의 값이 가장 크거나 인덱스 l, r이 범위를 벗어나면 힙을 더 재정렬할 필요가 없으므로 종료한다
if (ma === i) {
break;
}
// 두 노드를 교환한다
[nums[i], nums[ma]] = [nums[ma], nums[i]];
// 아래쪽으로 힙 재정렬을 반복한다
i = ma;
}
}
/* 힙 정렬 */
function heapSort(nums) {
// 힙 구성 연산: 리프 노드를 제외한 모든 노드에 힙 재정렬을 수행한다
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
siftDown(nums, nums.length, i);
}
// 힙에서 최댓값을 꺼내는 작업을 n-1회 반복한다
for (let i = nums.length - 1; i > 0; i--) {
// 루트 노드와 가장 오른쪽 리프 노드를 교환한다(첫 원소와 마지막 원소 교환)
[nums[0], nums[i]] = [nums[i], nums[0]];
// 루트 노드에서 시작하여 위에서 아래로 힙을 재정렬한다
siftDown(nums, i, 0);
}
}
/* 실행 코드 */
const nums = [4, 1, 3, 1, 5, 2];
heapSort(nums);
console.log('힙 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,25 @@
/**
* File: insertion_sort.js
* Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 삽입 정렬 */
function insertionSort(nums) {
// 바깥쪽 반복문: 정렬된 구간은 [0, i-1]이다
for (let i = 1; i < nums.length; i++) {
let base = nums[i],
j = i - 1;
// 안쪽 반복문: base를 정렬된 구간 [0, i-1]의 올바른 위치에 삽입한다
while (j >= 0 && nums[j] > base) {
nums[j + 1] = nums[j]; // nums[j]를 오른쪽으로 한 칸 이동한다
j--;
}
nums[j + 1] = base; // 올바른 위치에 base를 대입한다
}
}
/* 실행 코드 */
const nums = [4, 1, 3, 1, 5, 2];
insertionSort(nums);
console.log('삽입 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,52 @@
/**
* File: merge_sort.js
* Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 왼쪽 부분 배열과 오른쪽 부분 배열 병합 */
function merge(nums, left, mid, right) {
// 왼쪽 부분 배열의 구간은 [left, mid]이고, 오른쪽 부분 배열의 구간은 [mid+1, right]이다
// 병합 결과를 저장할 임시 배열 tmp를 생성한다
const tmp = new Array(right - left + 1);
// 왼쪽 부분 배열과 오른쪽 부분 배열의 시작 인덱스를 초기화한다
let i = left,
j = mid + 1,
k = 0;
// 양쪽 부분 배열 모두에 원소가 남아 있으면 비교하여 더 작은 원소를 임시 배열에 복사한다
while (i <= mid && j <= right) {
if (nums[i] <= nums[j]) {
tmp[k++] = nums[i++];
} else {
tmp[k++] = nums[j++];
}
}
// 왼쪽 부분 배열과 오른쪽 부분 배열의 남은 원소를 임시 배열에 복사한다
while (i <= mid) {
tmp[k++] = nums[i++];
}
while (j <= right) {
tmp[k++] = nums[j++];
}
// 임시 배열 tmp의 원소를 원래 배열 nums의 해당 구간에 다시 복사한다
for (k = 0; k < tmp.length; k++) {
nums[left + k] = tmp[k];
}
}
/* 병합 정렬 */
function mergeSort(nums, left, right) {
// 종료 조건
if (left >= right) return; // 부분 배열의 길이가 1이면 재귀를 종료한다
// 분할 단계
let mid = Math.floor(left + (right - left) / 2); // 중간 위치를 계산한다
mergeSort(nums, left, mid); // 왼쪽 부분 배열에 재귀 호출한다
mergeSort(nums, mid + 1, right); // 오른쪽 부분 배열에 재귀 호출한다
// 병합 단계
merge(nums, left, mid, right);
}
/* 실행 코드 */
const nums = [7, 3, 2, 6, 0, 1, 5, 4];
mergeSort(nums, 0, nums.length - 1);
console.log('병합 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,161 @@
/**
* File: quick_sort.js
* Created Time: 2022-12-01
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 퀵 정렬 클래스 */
class QuickSort {
/* 원소 교환 */
swap(nums, i, j) {
let tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 센티널 분할 */
partition(nums, left, right) {
// nums[left]를 피벗으로 삼는다
let i = left,
j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left]) {
j -= 1; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
}
while (i < j && nums[i] <= nums[left]) {
i += 1; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
}
// 원소 교환
this.swap(nums, i, j); // 두 원소를 교환한다
}
this.swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬 */
quickSort(nums, left, right) {
// 부분 배열의 길이가 1이면 재귀를 종료한다
if (left >= right) return;
// 센티널 분할
const pivot = this.partition(nums, left, right);
// 왼쪽 부분 배열과 오른쪽 부분 배열에 재귀 호출한다
this.quickSort(nums, left, pivot - 1);
this.quickSort(nums, pivot + 1, right);
}
}
/* 퀵 정렬 클래스(중앙값 피벗 최적화) */
class QuickSortMedian {
/* 원소 교환 */
swap(nums, i, j) {
let tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 세 후보 원소의 중앙값 선택 */
medianThree(nums, left, mid, right) {
let l = nums[left],
m = nums[mid],
r = nums[right];
// m은 l과 r 사이에 있다
if ((l <= m && m <= r) || (r <= m && m <= l)) return mid;
// l은 m과 r 사이에 있다
if ((m <= l && l <= r) || (r <= l && l <= m)) return left;
return right;
}
/* 센티널 분할(세 수의 중앙값 선택) */
partition(nums, left, right) {
// 세 후보 원소의 중앙값 선택
let med = this.medianThree(
nums,
left,
Math.floor((left + right) / 2),
right
);
// 중앙값을 배열 맨 왼쪽으로 교환하여 옮긴다
this.swap(nums, left, med);
// nums[left]를 피벗으로 삼는다
let i = left,
j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left]) j--; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
while (i < j && nums[i] <= nums[left]) i++; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
this.swap(nums, i, j); // 두 원소를 교환한다
}
this.swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬 */
quickSort(nums, left, right) {
// 부분 배열의 길이가 1이면 재귀를 종료한다
if (left >= right) return;
// 센티널 분할
const pivot = this.partition(nums, left, right);
// 왼쪽 부분 배열과 오른쪽 부분 배열에 재귀 호출한다
this.quickSort(nums, left, pivot - 1);
this.quickSort(nums, pivot + 1, right);
}
}
/* 퀵 정렬 클래스(재귀 깊이 최적화) */
class QuickSortTailCall {
/* 원소 교환 */
swap(nums, i, j) {
let tmp = nums[i];
nums[i] = nums[j];
nums[j] = tmp;
}
/* 센티널 분할 */
partition(nums, left, right) {
// nums[left]를 피벗으로 삼는다
let i = left,
j = right;
while (i < j) {
while (i < j && nums[j] >= nums[left]) j--; // 오른쪽에서 왼쪽으로 피벗보다 작은 첫 번째 원소를 찾는다
while (i < j && nums[i] <= nums[left]) i++; // 왼쪽에서 오른쪽으로 피벗보다 큰 첫 번째 원소를 찾는다
this.swap(nums, i, j); // 두 원소를 교환한다
}
this.swap(nums, i, left); // 피벗을 두 부분 배열의 경계로 교환하여 옮긴다
return i; // 피벗의 인덱스를 반환한다
}
/* 퀵 정렬(재귀 깊이 최적화) */
quickSort(nums, left, right) {
// 부분 배열의 길이가 1이면 종료한다
while (left < right) {
// 센티널 분할 연산
let pivot = this.partition(nums, left, right);
// 두 부분 배열 중 더 짧은 쪽에 퀵 정렬을 수행한다
if (pivot - left < right - pivot) {
this.quickSort(nums, left, pivot - 1); // 왼쪽 부분 배열을 재귀적으로 정렬한다
left = pivot + 1; // 남은 미정렬 구간은 [pivot + 1, right]이다
} else {
this.quickSort(nums, pivot + 1, right); // 오른쪽 부분 배열을 재귀적으로 정렬한다
right = pivot - 1; // 남은 미정렬 구간은 [left, pivot - 1]이다
}
}
}
}
/* 실행 코드 */
/* 퀵 정렬 */
const nums = [2, 4, 1, 0, 3, 5];
const quickSort = new QuickSort();
quickSort.quickSort(nums, 0, nums.length - 1);
console.log('퀵 정렬을 마친 후 nums =', nums);
/* 퀵 정렬(중앙값 피벗 최적화) */
const nums1 = [2, 4, 1, 0, 3, 5];
const quickSortMedian = new QuickSortMedian();
quickSortMedian.quickSort(nums1, 0, nums1.length - 1);
console.log('퀵 정렬(중앙값 피벗 최적화)을 마친 후 nums =', nums1);
/* 퀵 정렬(재귀 깊이 최적화) */
const nums2 = [2, 4, 1, 0, 3, 5];
const quickSortTailCall = new QuickSortTailCall();
quickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
console.log('퀵 정렬(재귀 깊이 최적화)을 마친 후 nums =', nums2);

View File

@@ -0,0 +1,61 @@
/**
* File: radix_sort.js
* Created Time: 2023-04-08
* Author: Justin (xiefahit@gmail.com)
*/
/* 원소 num의 k번째 자릿값 반환. 이때 exp = 10^(k-1)이다 */
function digit(num, exp) {
// k 대신 exp를 전달하면 여기서 비용이 큰 거듭제곱 계산을 반복하지 않아도 된다
return Math.floor(num / exp) % 10;
}
/* 계수 정렬(nums의 k번째 자릿값을 기준으로 정렬) */
function countingSortDigit(nums, exp) {
// 십진수의 각 자리는 0~9 범위이므로 길이가 10인 버킷 배열이 필요하다
const counter = new Array(10).fill(0);
const n = nums.length;
// 0~9 각 숫자의 등장 횟수를 센다
for (let i = 0; i < n; i++) {
const d = digit(nums[i], exp); // nums[i]의 k번째 자릿값을 구하여 d로 표시한다
counter[d]++; // 숫자 d의 등장 횟수를 센다
}
// 접두 합을 구하여 등장 개수를 배열 인덱스로 변환한다
for (let i = 1; i < 10; i++) {
counter[i] += counter[i - 1];
}
// 역순으로 순회하며 버킷에 집계된 결과에 따라 각 원소를 res에 채운다
const res = new Array(n).fill(0);
for (let i = n - 1; i >= 0; i--) {
const d = digit(nums[i], exp);
const j = counter[d] - 1; // 배열에서 d의 인덱스 j를 구한다
res[j] = nums[i]; // 현재 원소를 인덱스 j에 채운다
counter[d]--; // d의 개수를 1 줄인다
}
// 결과로 원래 배열 nums를 덮어쓴다
for (let i = 0; i < n; i++) {
nums[i] = res[i];
}
}
/* 기수 정렬 */
function radixSort(nums) {
// 배열의 최댓값을 구하여 최대 자릿수를 판단한다
let m = Math.max(... nums);
// 낮은 자리에서 높은 자리 순서로 순회한다
for (let exp = 1; exp <= m; exp *= 10) {
// 배열 원소의 k번째 자릿값에 대해 계수 정렬을 수행한다
// k = 1 -> exp = 1
// k = 2 -> exp = 10
// 즉, exp = 10^(k-1)이다
countingSortDigit(nums, exp);
}
}
/* 실행 코드 */
const nums = [
10546151, 35663510, 42865989, 34862445, 81883077, 88906420, 72429244,
30524779, 82060337, 63832996,
];
radixSort(nums);
console.log('기수 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,27 @@
/**
* File: selection_sort.js
* Created Time: 2023-06-04
* Author: Justin (xiefahit@gmail.com)
*/
/* 선택 정렬 */
function selectionSort(nums) {
let n = nums.length;
// 바깥쪽 반복문: 정렬되지 않은 구간은 [i, n-1]이다
for (let i = 0; i < n - 1; i++) {
// 안쪽 반복문: 정렬되지 않은 구간의 최솟값을 찾는다
let k = i;
for (let j = i + 1; j < n; j++) {
if (nums[j] < nums[k]) {
k = j; // 최솟값의 인덱스를 기록한다
}
}
// 이 최솟값과 정렬되지 않은 구간의 첫 원소를 교환한다
[nums[i], nums[k]] = [nums[k], nums[i]];
}
}
/* 실행 코드 */
const nums = [4, 1, 3, 1, 5, 2];
selectionSort(nums);
console.log('선택 정렬을 마친 후 nums =', nums);

View File

@@ -0,0 +1,156 @@
/**
* File: array_deque.js
* Created Time: 2023-02-28
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
/* 원형 배열로 구현한 덱 */
class ArrayDeque {
#nums; // 덱의 원소를 저장하는 배열
#front; // 맨 앞 원소를 가리키는 맨 앞 포인터
#queSize; // 덱 길이
/* 생성자 */
constructor(capacity) {
this.#nums = new Array(capacity);
this.#front = 0;
this.#queSize = 0;
}
/* 덱의 용량 반환 */
capacity() {
return this.#nums.length;
}
/* 덱의 길이 반환 */
size() {
return this.#queSize;
}
/* 덱이 비어 있는지 판단 */
isEmpty() {
return this.#queSize === 0;
}
/* 원형 배열 인덱스 계산 */
index(i) {
// 나머지 연산을 통해 배열의 처음과 끝을 연결한다
// i가 배열의 끝을 넘어가면 처음으로 돌아온다
// i가 배열의 처음을 넘어가면 끝으로 돌아온다
return (i + this.capacity()) % this.capacity();
}
/* 맨 앞에 삽입 */
pushFirst(num) {
if (this.#queSize === this.capacity()) {
console.log('덱이 가득 찼다');
return;
}
// 맨 앞 포인터를 왼쪽으로 한 칸 이동한다
// 나머지 연산을 통해 front가 배열의 처음을 넘어가면 끝으로 돌아오게 한다
this.#front = this.index(this.#front - 1);
// num을 맨 앞에 추가한다
this.#nums[this.#front] = num;
this.#queSize++;
}
/* 맨 뒤에 삽입 */
pushLast(num) {
if (this.#queSize === this.capacity()) {
console.log('덱이 가득 찼다');
return;
}
// 맨 뒤 인덱스 + 1을 가리키는 맨 뒤 포인터를 계산한다
const rear = this.index(this.#front + this.#queSize);
// num을 맨 뒤에 추가한다
this.#nums[rear] = num;
this.#queSize++;
}
/* 맨 앞에서 꺼내기 */
popFirst() {
const num = this.peekFirst();
// 맨 앞 포인터를 뒤로 한 칸 이동한다
this.#front = this.index(this.#front + 1);
this.#queSize--;
return num;
}
/* 맨 뒤에서 꺼내기 */
popLast() {
const num = this.peekLast();
this.#queSize--;
return num;
}
/* 맨 앞 원소 접근 */
peekFirst() {
if (this.isEmpty()) throw new Error('덱이 비어 있다.');
return this.#nums[this.#front];
}
/* 맨 뒤 원소 접근 */
peekLast() {
if (this.isEmpty()) throw new Error('덱이 비어 있다.');
// 마지막 원소의 인덱스를 계산한다
const last = this.index(this.#front + this.#queSize - 1);
return this.#nums[last];
}
/* 출력에 사용할 배열 반환 */
toArray() {
// 유효한 길이 범위 안의 리스트 원소만 변환한다
const res = [];
for (let i = 0, j = this.#front; i < this.#queSize; i++, j++) {
res[i] = this.#nums[this.index(j)];
}
return res;
}
}
/* 실행 코드 */
/* 덱 초기화 */
const capacity = 5;
const deque = new ArrayDeque(capacity);
deque.pushLast(3);
deque.pushLast(2);
deque.pushLast(5);
console.log('덱 deque = [' + deque.toArray() + ']');
/* 원소 접근 */
const peekFirst = deque.peekFirst();
console.log('맨 앞 원소 peekFirst = ' + peekFirst);
const peekLast = deque.peekLast();
console.log('맨 뒤 원소 peekLast = ' + peekLast);
/* 큐에 원소 삽입 */
deque.pushLast(4);
console.log('뒤쪽에 원소 4를 삽입한 후 deque = [' + deque.toArray() + ']');
deque.pushFirst(1);
console.log('앞쪽에 원소 1을 삽입한 후 deque = [' + deque.toArray() + ']');
/* 큐에서 원소 꺼내기 */
const popLast = deque.popLast();
console.log(
'맨 뒤에서 꺼낸 원소 = ' +
popLast +
', 뒤쪽 원소를 꺼낸 후 deque = [' +
deque.toArray() +
']'
);
const popFirst = deque.popFirst();
console.log(
'맨 앞에서 꺼낸 원소 = ' +
popFirst +
', 앞쪽 원소를 꺼낸 후 deque = [' +
deque.toArray() +
']'
);
/* 덱의 길이 반환 */
const size = deque.size();
console.log('덱 길이 size = ' + size);
/* 덱이 비어 있는지 판단 */
const isEmpty = deque.isEmpty();
console.log('덱이 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,106 @@
/**
* File: array_queue.js
* Created Time: 2022-12-13
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 원형 배열로 구현한 큐 */
class ArrayQueue {
#nums; // 큐의 원소를 저장하는 배열
#front = 0; // 맨 앞 원소를 가리키는 맨 앞 포인터
#queSize = 0; // 큐 길이
constructor(capacity) {
this.#nums = new Array(capacity);
}
/* 큐의 용량 반환 */
get capacity() {
return this.#nums.length;
}
/* 큐의 길이 반환 */
get size() {
return this.#queSize;
}
/* 큐가 비어 있는지 판단 */
isEmpty() {
return this.#queSize === 0;
}
/* 큐에 삽입 */
push(num) {
if (this.size === this.capacity) {
console.log('큐가 가득 찼다');
return;
}
// 맨 뒤 인덱스 + 1을 가리키는 맨 뒤 포인터를 계산한다
// 나머지 연산을 통해 rear가 배열의 끝을 넘어가면 처음으로 돌아오게 한다
const rear = (this.#front + this.size) % this.capacity;
// num을 맨 뒤에 추가한다
this.#nums[rear] = num;
this.#queSize++;
}
/* 큐에서 꺼내기 */
pop() {
const num = this.peek();
// 맨 앞 포인터를 뒤로 한 칸 이동하고, 끝을 넘어가면 배열의 처음으로 돌아온다
this.#front = (this.#front + 1) % this.capacity;
this.#queSize--;
return num;
}
/* 맨 앞 원소 접근 */
peek() {
if (this.isEmpty()) throw new Error('큐가 비어 있다');
return this.#nums[this.#front];
}
/* Array를 반환한다 */
toArray() {
// 유효한 길이 범위 안의 리스트 원소만 변환한다
const arr = new Array(this.size);
for (let i = 0, j = this.#front; i < this.size; i++, j++) {
arr[i] = this.#nums[j % this.capacity];
}
return arr;
}
}
/* 실행 코드 */
/* 큐 초기화 */
const capacity = 10;
const queue = new ArrayQueue(capacity);
/* 큐에 원소 삽입 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
console.log('큐 queue =', queue.toArray());
/* 맨 앞 원소 접근 */
const peek = queue.peek();
console.log('맨 앞 원소 peek = ' + peek);
/* 큐에서 원소 꺼내기 */
const pop = queue.pop();
console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue =', queue.toArray());
/* 큐의 길이 반환 */
const size = queue.size;
console.log('큐 길이 size = ' + size);
/* 큐가 비어 있는지 판단 */
const isEmpty = queue.isEmpty();
console.log('큐가 비어 있는가 = ' + isEmpty);
/* 원형 배열 테스트 */
for (let i = 0; i < 10; i++) {
queue.push(i);
queue.pop();
console.log('반복 ' + i + ' 회에서 삽입 + 꺼내기를 수행한 후 queue =', queue.toArray());
}

View File

@@ -0,0 +1,75 @@
/**
* File: array_stack.js
* Created Time: 2022-12-09
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 배열로 구현한 스택 */
class ArrayStack {
#stack;
constructor() {
this.#stack = [];
}
/* 스택의 길이 반환 */
get size() {
return this.#stack.length;
}
/* 스택이 비어 있는지 판단 */
isEmpty() {
return this.#stack.length === 0;
}
/* 스택에 삽입 */
push(num) {
this.#stack.push(num);
}
/* 스택에서 꺼내기 */
pop() {
if (this.isEmpty()) throw new Error('스택이 비어 있다');
return this.#stack.pop();
}
/* 스택 맨 위 원소 접근 */
top() {
if (this.isEmpty()) throw new Error('스택이 비어 있다');
return this.#stack[this.#stack.length - 1];
}
/* Array를 반환한다 */
toArray() {
return this.#stack;
}
}
/* 실행 코드 */
/* 스택 초기화 */
const stack = new ArrayStack();
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
console.log('스택 stack = ');
console.log(stack.toArray());
/* 스택 맨 위 원소 접근 */
const top = stack.top();
console.log('스택의 맨 위 원소 top = ' + top);
/* 스택에서 원소 꺼내기 */
const pop = stack.pop();
console.log('스택에서 꺼낸 원소 pop = ' + pop + ', 스택에서 꺼낸 후 stack = ');
console.log(stack.toArray());
/* 스택의 길이 반환 */
const size = stack.size;
console.log('스택의 길이 size = ' + size);
/* 비어 있는지 판단 */
const isEmpty = stack.isEmpty();
console.log('스택이 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,44 @@
/**
* File: deque.js
* Created Time: 2023-01-17
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
/* 실행 코드 */
/* 덱 초기화 */
// JavaScript에는 내장 덱이 없으므로 Array를 덱으로 사용한다
const deque = [];
/* 큐에 원소 삽입 */
deque.push(2);
deque.push(5);
deque.push(4);
// 배열이므로 unshift() 메서드의 시간 복잡도는 O(n)임에 유의한다
deque.unshift(3);
deque.unshift(1);
console.log('덱 deque = ', deque);
/* 원소 접근 */
const peekFirst = deque[0];
console.log('맨 앞 원소 peekFirst = ' + peekFirst);
const peekLast = deque[deque.length - 1];
console.log('맨 뒤 원소 peekLast = ' + peekLast);
/* 큐에서 원소 꺼내기 */
// 배열이므로 shift() 메서드의 시간 복잡도는 O(n)임에 유의한다
const popFront = deque.shift();
console.log(
'맨 앞에서 꺼낸 원소 popFront = ' + popFront + ', 맨 앞에서 꺼낸 후 deque = ' + deque
);
const popBack = deque.pop();
console.log(
'뒤쪽에서 꺼낸 원소 popBack = ' + popBack + ', 맨 뒤에서 꺼낸 후 deque = ' + deque
);
/* 덱의 길이 반환 */
const size = deque.length;
console.log('덱 길이 size = ' + size);
/* 덱이 비어 있는지 판단 */
const isEmpty = size === 0;
console.log('덱이 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,177 @@
/**
* File: linkedlist_deque.js
* Created Time: 2023-02-04
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
/* 이중 연결 리스트 노드 */
class ListNode {
prev; // 이전 노드 참조(포인터)
next; // 다음 노드 참조(포인터)
val; // 노드 값
constructor(val) {
this.val = val;
this.next = null;
this.prev = null;
}
}
/* 이중 연결 리스트로 구현한 덱 */
class LinkedListDeque {
#front; // 머리 노드 front
#rear; // 꼬리 노드 rear
#queSize; // 덱의 길이
constructor() {
this.#front = null;
this.#rear = null;
this.#queSize = 0;
}
/* 맨 뒤에 삽입하는 연산 */
pushLast(val) {
const node = new ListNode(val);
// 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다
if (this.#queSize === 0) {
this.#front = node;
this.#rear = node;
} else {
// node를 연결 리스트의 맨 뒤에 추가한다
this.#rear.next = node;
node.prev = this.#rear;
this.#rear = node; // 꼬리 노드를 갱신한다
}
this.#queSize++;
}
/* 맨 앞에 삽입하는 연산 */
pushFirst(val) {
const node = new ListNode(val);
// 연결 리스트가 비어 있으면 front와 rear가 모두 node를 가리키게 한다
if (this.#queSize === 0) {
this.#front = node;
this.#rear = node;
} else {
// node를 연결 리스트의 맨 앞에 추가한다
this.#front.prev = node;
node.next = this.#front;
this.#front = node; // 머리 노드를 갱신한다
}
this.#queSize++;
}
/* 맨 뒤에서 꺼내는 연산 */
popLast() {
if (this.#queSize === 0) {
return null;
}
const value = this.#rear.val; // 꼬리 노드의 값을 저장한다
// 큐의 길이가 1이면 머리와 꼬리가 같은 노드를 가리킨다
if (this.#queSize === 1) {
this.#front = null;
this.#rear = null;
}
// 꼬리 노드를 삭제한다
else {
let temp = this.#rear.prev;
temp.next = null;
this.#rear.prev = null;
this.#rear = temp; // 꼬리 노드를 갱신한다
}
this.#queSize--;
return value;
}
/* 맨 앞에서 꺼내는 연산 */
popFirst() {
if (this.#queSize === 0) {
return null;
}
const value = this.#front.val; // 머리 노드의 값을 저장한다
// 큐의 길이가 1이면 머리와 꼬리가 같은 노드를 가리킨다
if (this.#queSize === 1) {
this.#front = null;
this.#rear = null;
}
// 머리 노드를 삭제한다
else {
let temp = this.#front.next;
temp.prev = null;
this.#front.next = null;
this.#front = temp; // 머리 노드를 갱신한다
}
this.#queSize--;
return value;
}
/* 맨 뒤 원소 접근 */
peekLast() {
return this.#queSize === 0 ? null : this.#rear.val;
}
/* 맨 앞 원소 접근 */
peekFirst() {
return this.#queSize === 0 ? null : this.#front.val;
}
/* 덱의 길이 반환 */
size() {
return this.#queSize;
}
/* 덱이 비어 있는지 판단 */
isEmpty() {
return this.#queSize === 0;
}
/* 덱을 출력한다 */
print() {
const arr = [];
let temp = this.#front;
while (temp !== null) {
arr.push(temp.val);
temp = temp.next;
}
console.log('[' + arr.join(', ') + ']');
}
}
/* 실행 코드 */
/* 덱 초기화 */
const linkedListDeque = new LinkedListDeque();
linkedListDeque.pushLast(3);
linkedListDeque.pushLast(2);
linkedListDeque.pushLast(5);
console.log('덱 linkedListDeque = ');
linkedListDeque.print();
/* 원소 접근 */
const peekFirst = linkedListDeque.peekFirst();
console.log('맨 앞 원소 peekFirst = ' + peekFirst);
const peekLast = linkedListDeque.peekLast();
console.log('맨 뒤 원소 peekLast = ' + peekLast);
/* 큐에 원소 삽입 */
linkedListDeque.pushLast(4);
console.log('뒤쪽에 원소 4를 삽입한 후 linkedListDeque = ');
linkedListDeque.print();
linkedListDeque.pushFirst(1);
console.log('앞쪽에 원소 1을 삽입한 후 linkedListDeque = ');
linkedListDeque.print();
/* 큐에서 원소 꺼내기 */
const popLast = linkedListDeque.popLast();
console.log('맨 뒤에서 꺼낸 원소 = ' + popLast + ', 뒤쪽 원소를 꺼낸 후 linkedListDeque = ');
linkedListDeque.print();
const popFirst = linkedListDeque.popFirst();
console.log('맨 앞에서 꺼낸 원소 = ' + popFirst + ', 앞쪽 원소를 꺼낸 후 linkedListDeque = ');
linkedListDeque.print();
/* 덱의 길이 반환 */
const size = linkedListDeque.size();
console.log('덱 길이 size = ' + size);
/* 덱이 비어 있는지 판단 */
const isEmpty = linkedListDeque.isEmpty();
console.log('덱이 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,99 @@
/**
* File: linkedlist_queue.js
* Created Time: 2022-12-20
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
const { ListNode } = require('../modules/ListNode');
/* 연결 리스트로 구현한 큐 */
class LinkedListQueue {
#front; // 머리 노드 #front
#rear; // 꼬리 노드 #rear
#queSize = 0;
constructor() {
this.#front = null;
this.#rear = null;
}
/* 큐의 길이 반환 */
get size() {
return this.#queSize;
}
/* 큐가 비어 있는지 판단 */
isEmpty() {
return this.size === 0;
}
/* 큐에 삽입 */
push(num) {
// 꼬리 노드 뒤에 num을 추가한다
const node = new ListNode(num);
// 큐가 비어 있으면 머리와 꼬리 노드가 모두 해당 노드를 가리키게 한다
if (!this.#front) {
this.#front = node;
this.#rear = node;
// 큐가 비어 있지 않으면 해당 노드를 꼬리 노드 뒤에 추가한다
} else {
this.#rear.next = node;
this.#rear = node;
}
this.#queSize++;
}
/* 큐에서 꺼내기 */
pop() {
const num = this.peek();
// 머리 노드를 삭제한다
this.#front = this.#front.next;
this.#queSize--;
return num;
}
/* 맨 앞 원소 접근 */
peek() {
if (this.size === 0) throw new Error('큐가 비어 있다');
return this.#front.val;
}
/* 연결 리스트를 Array로 변환하여 반환 */
toArray() {
let node = this.#front;
const res = new Array(this.size);
for (let i = 0; i < res.length; i++) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
/* 실행 코드 */
/* 큐 초기화 */
const queue = new LinkedListQueue();
/* 큐에 원소 삽입 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
console.log('큐 queue = ' + queue.toArray());
/* 맨 앞 원소 접근 */
const peek = queue.peek();
console.log('맨 앞 원소 peek = ' + peek);
/* 큐에서 원소 꺼내기 */
const pop = queue.pop();
console.log('큐에서 꺼낸 원소 pop = ' + pop + ', 큐에서 꺼낸 후 queue = ' + queue.toArray());
/* 큐의 길이 반환 */
const size = queue.size;
console.log('큐 길이 size = ' + size);
/* 큐가 비어 있는지 판단 */
const isEmpty = queue.isEmpty();
console.log('큐가 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,88 @@
/**
* File: linkedlist_stack.js
* Created Time: 2022-12-22
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
const { ListNode } = require('../modules/ListNode');
/* 연결 리스트로 구현한 스택 */
class LinkedListStack {
#stackPeek; // 머리 노드를 스택의 맨 위로 사용한다
#stkSize = 0; // 스택의 길이
constructor() {
this.#stackPeek = null;
}
/* 스택의 길이 반환 */
get size() {
return this.#stkSize;
}
/* 스택이 비어 있는지 판단 */
isEmpty() {
return this.size === 0;
}
/* 스택에 삽입 */
push(num) {
const node = new ListNode(num);
node.next = this.#stackPeek;
this.#stackPeek = node;
this.#stkSize++;
}
/* 스택에서 꺼내기 */
pop() {
const num = this.peek();
this.#stackPeek = this.#stackPeek.next;
this.#stkSize--;
return num;
}
/* 스택 맨 위 원소 접근 */
peek() {
if (!this.#stackPeek) throw new Error('스택이 비어 있다');
return this.#stackPeek.val;
}
/* 연결 리스트를 Array로 변환하여 반환 */
toArray() {
let node = this.#stackPeek;
const res = new Array(this.size);
for (let i = res.length - 1; i >= 0; i--) {
res[i] = node.val;
node = node.next;
}
return res;
}
}
/* 실행 코드 */
/* 스택 초기화 */
const stack = new LinkedListStack();
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
console.log('스택 stack = ' + stack.toArray());
/* 스택 맨 위 원소 접근 */
const peek = stack.peek();
console.log('스택 맨 위 원소 peek = ' + peek);
/* 스택에서 원소 꺼내기 */
const pop = stack.pop();
console.log('스택에서 꺼낸 원소 pop = ' + pop + ', 스택에서 꺼낸 후 stack = ' + stack.toArray());
/* 스택의 길이 반환 */
const size = stack.size;
console.log('스택의 길이 size = ' + size);
/* 비어 있는지 판단 */
const isEmpty = stack.isEmpty();
console.log('스택이 비어 있는가 = ' + isEmpty);

View File

@@ -0,0 +1,35 @@
/**
* File: queue.js
* Created Time: 2022-12-05
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 실행 코드 */
/* 큐 초기화 */
// JavaScript에는 내장 큐가 없으므로 Array를 큐로 사용할 수 있다
const queue = [];
/* 큐에 원소 삽입 */
queue.push(1);
queue.push(3);
queue.push(2);
queue.push(5);
queue.push(4);
console.log('큐 queue =', queue);
/* 맨 앞 원소 접근 */
const peek = queue[0];
console.log('맨 앞 원소 peek =', peek);
/* 큐에서 원소 꺼내기 */
// 내부 자료 구조가 배열이므로 shift() 메서드의 시간 복잡도는 O(n)이다
const pop = queue.shift();
console.log('큐에서 꺼낸 원소 pop =', pop, ', 큐에서 꺼낸 후 queue = ', queue);
/* 큐의 길이 반환 */
const size = queue.length;
console.log('큐 길이 size =', size);
/* 큐가 비어 있는지 판단 */
const isEmpty = queue.length === 0;
console.log('큐가 비어 있는가 = ', isEmpty);

View File

@@ -0,0 +1,35 @@
/**
* File: stack.js
* Created Time: 2022-12-04
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
*/
/* 실행 코드 */
/* 스택 초기화 */
// JavaScript에는 내장 스택 클래스가 없으므로 Array를 스택으로 사용할 수 있다
const stack = [];
/* 스택에 원소 삽입 */
stack.push(1);
stack.push(3);
stack.push(2);
stack.push(5);
stack.push(4);
console.log('스택 stack =', stack);
/* 스택 맨 위 원소 접근 */
const peek = stack[stack.length - 1];
console.log('스택 맨 위 원소 peek =', peek);
/* 스택에서 원소 꺼내기 */
const pop = stack.pop();
console.log('스택에서 꺼낸 원소 pop =', pop);
console.log('스택에서 꺼낸 후 stack =', stack);
/* 스택의 길이 반환 */
const size = stack.length;
console.log('스택의 길이 size =', size);
/* 비어 있는지 판단 */
const isEmpty = stack.length === 0;
console.log('스택이 비어 있는가 =', isEmpty);

View File

@@ -0,0 +1,147 @@
/**
* File: array_binary_tree.js
* Created Time: 2023-08-06
* Author: yuan0221 (yl1452491917@gmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 배열로 표현한 이진 트리 클래스 */
class ArrayBinaryTree {
#tree;
/* 생성자 */
constructor(arr) {
this.#tree = arr;
}
/* 리스트 용량 */
size() {
return this.#tree.length;
}
/* 인덱스가 i인 노드의 값 반환 */
val(i) {
// 인덱스가 범위를 벗어나면 빈칸을 나타내는 null을 반환한다
if (i < 0 || i >= this.size()) return null;
return this.#tree[i];
}
/* 인덱스가 i인 노드의 왼쪽 자식 노드 인덱스 반환 */
left(i) {
return 2 * i + 1;
}
/* 인덱스가 i인 노드의 오른쪽 자식 노드 인덱스 반환 */
right(i) {
return 2 * i + 2;
}
/* 인덱스가 i인 노드의 부모 노드 인덱스 반환 */
parent(i) {
return Math.floor((i - 1) / 2); // 나눗셈의 결과를 내림한다
}
/* 레벨 순서 순회 */
levelOrder() {
let res = [];
// 배열을 직접 순회한다
for (let i = 0; i < this.size(); i++) {
if (this.val(i) !== null) res.push(this.val(i));
}
return res;
}
/* 깊이 우선 순회 */
#dfs(i, order, res) {
// 빈칸이면 반환한다
if (this.val(i) === null) return;
// 전위 순회
if (order === 'pre') res.push(this.val(i));
this.#dfs(this.left(i), order, res);
// 중위 순회
if (order === 'in') res.push(this.val(i));
this.#dfs(this.right(i), order, res);
// 후위 순회
if (order === 'post') res.push(this.val(i));
}
/* 전위 순회 */
preOrder() {
const res = [];
this.#dfs(0, 'pre', res);
return res;
}
/* 중위 순회 */
inOrder() {
const res = [];
this.#dfs(0, 'in', res);
return res;
}
/* 후위 순회 */
postOrder() {
const res = [];
this.#dfs(0, 'post', res);
return res;
}
}
/* 실행 코드 */
// 이진 트리 초기화
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
const arr = Array.of(
1,
2,
3,
4,
null,
6,
7,
8,
9,
null,
null,
12,
null,
null,
15
);
const root = arrToTree(arr);
console.log('\n이진 트리 초기화\n');
console.log('이진 트리의 배열 표현:');
console.log(arr);
console.log('이진 트리의 연결 리스트 표현:');
printTree(root);
// 배열로 표현한 이진 트리 클래스
const abt = new ArrayBinaryTree(arr);
// 노드 접근
const i = 1;
const l = abt.left(i);
const r = abt.right(i);
const p = abt.parent(i);
console.log('\n현재 노드의 인덱스: ' + i + ' , 값: ' + abt.val(i));
console.log(
'왼쪽 자식 노드의 인덱스: ' + l + ' , 값: ' + (l === null ? 'null' : abt.val(l))
);
console.log(
'오른쪽 자식 노드의 인덱스: ' + r + ' , 값: ' + (r === null ? 'null' : abt.val(r))
);
console.log(
'부모 노드의 인덱스: ' + p + ' , 값: ' + (p === null ? 'null' : abt.val(p))
);
// 트리 순회
let res = abt.levelOrder();
console.log('\n레벨 순서 순회:' + res);
res = abt.preOrder();
console.log('전위 순회:' + res);
res = abt.inOrder();
console.log('중위 순회:' + res);
res = abt.postOrder();
console.log('후위 순회:' + res);

View File

@@ -0,0 +1,208 @@
/**
* File: avl_tree.js
* Created Time: 2023-02-05
* Author: what-is-me (whatisme@outlook.jp)
*/
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* AVL 트리*/
class AVLTree {
/* 생성자 */
constructor() {
this.root = null; //루트 노드
}
/* 노드 높이 반환 */
height(node) {
// 빈 노드의 높이는 -1이고, 리프 노드의 높이는 0이다
return node === null ? -1 : node.height;
}
/* 노드 높이를 갱신한다 */
#updateHeight(node) {
// 노드 높이는 가장 높은 서브트리의 높이 + 1이다
node.height =
Math.max(this.height(node.left), this.height(node.right)) + 1;
}
/* 균형 인수 반환 */
balanceFactor(node) {
// 빈 노드의 균형 인수는 0이다
if (node === null) return 0;
// 노드의 균형 인수 = 왼쪽 서브트리 높이 - 오른쪽 서브트리 높이
return this.height(node.left) - this.height(node.right);
}
/* 오른쪽 회전 연산 */
#rightRotate(node) {
const child = node.left;
const grandChild = child.right;
// child를 중심으로 node를 오른쪽으로 회전한다
child.right = node;
node.left = grandChild;
// 노드 높이를 갱신한다
this.#updateHeight(node);
this.#updateHeight(child);
// 회전한 서브트리의 루트 노드를 반환한다
return child;
}
/* 왼쪽 회전 연산 */
#leftRotate(node) {
const child = node.right;
const grandChild = child.left;
// child를 중심으로 node를 왼쪽으로 회전한다
child.left = node;
node.right = grandChild;
// 노드 높이를 갱신한다
this.#updateHeight(node);
this.#updateHeight(child);
// 회전한 서브트리의 루트 노드를 반환한다
return child;
}
/* 회전 연산을 수행하여 해당 서브트리의 균형 복원 */
#rotate(node) {
// 노드 node의 균형 인수를 구한다
const balanceFactor = this.balanceFactor(node);
// 왼쪽으로 치우친 트리
if (balanceFactor > 1) {
if (this.balanceFactor(node.left) >= 0) {
// 오른쪽 회전
return this.#rightRotate(node);
} else {
// 왼쪽으로 회전한 후 오른쪽으로 회전한다
node.left = this.#leftRotate(node.left);
return this.#rightRotate(node);
}
}
// 오른쪽으로 치우친 트리
if (balanceFactor < -1) {
if (this.balanceFactor(node.right) <= 0) {
// 왼쪽 회전
return this.#leftRotate(node);
} else {
// 오른쪽으로 회전한 후 왼쪽으로 회전한다
node.right = this.#rightRotate(node.right);
return this.#leftRotate(node);
}
}
// 균형 트리이므로 회전할 필요 없이 바로 반환한다
return node;
}
/* 노드 삽입 */
insert(val) {
this.root = this.#insertHelper(this.root, val);
}
/* 노드의 재귀적 삽입(보조 메서드) */
#insertHelper(node, val) {
if (node === null) return new TreeNode(val);
/* 1. 삽입 위치를 찾아 노드를 삽입한다 */
if (val < node.val) node.left = this.#insertHelper(node.left, val);
else if (val > node.val)
node.right = this.#insertHelper(node.right, val);
else return node; // 중복 노드는 삽입하지 않고 바로 반환한다
this.#updateHeight(node); // 노드 높이를 갱신한다
/* 2. 회전 연산을 수행하여 해당 서브트리의 균형을 복원한다 */
node = this.#rotate(node);
// 서브트리의 루트 노드를 반환한다
return node;
}
/* 노드 삭제 */
remove(val) {
this.root = this.#removeHelper(this.root, val);
}
/* 노드의 재귀적 삭제(보조 메서드) */
#removeHelper(node, val) {
if (node === null) return null;
/* 1. 노드를 찾아 삭제한다 */
if (val < node.val) node.left = this.#removeHelper(node.left, val);
else if (val > node.val)
node.right = this.#removeHelper(node.right, val);
else {
if (node.left === null || node.right === null) {
const child = node.left !== null ? node.left : node.right;
// 자식 노드 수 = 0이면 node를 바로 삭제하고 반환한다
if (child === null) return null;
// 자식 노드 수 = 1이면 node를 바로 삭제한다
else node = child;
} else {
// 자식 노드 수 = 2이면 중위 순회의 다음 노드를 삭제하고, 그 노드로 현재 노드를 대체한다
let temp = node.right;
while (temp.left !== null) {
temp = temp.left;
}
node.right = this.#removeHelper(node.right, temp.val);
node.val = temp.val;
}
}
this.#updateHeight(node); // 노드 높이를 갱신한다
/* 2. 회전 연산을 수행하여 해당 서브트리의 균형을 복원한다 */
node = this.#rotate(node);
// 서브트리의 루트 노드를 반환한다
return node;
}
/* 노드 탐색 */
search(val) {
let cur = this.root;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur !== null) {
// 목표 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < val) cur = cur.right;
// 목표 노드는 cur의 왼쪽 서브트리에 있다
else if (cur.val > val) cur = cur.left;
// 목표 노드를 찾았으므로 반복문을 종료한다
else break;
}
// 목표 노드를 반환한다
return cur;
}
}
function testInsert(tree, val) {
tree.insert(val);
console.log('\n노드 삽입: ' + val + ' ; 연산 후 AVL 트리');
printTree(tree.root);
}
function testRemove(tree, val) {
tree.remove(val);
console.log('\n노드 삭제: ' + val + ' ; 연산 후 AVL 트리');
printTree(tree.root);
}
/* 실행 코드 */
/* 빈 AVL 트리 초기화 */
const avlTree = new AVLTree();
/* 노드 삽입 */
// 노드를 삽입한 후 AVL 트리가 어떻게 균형을 유지하는지 살펴본다
testInsert(avlTree, 1);
testInsert(avlTree, 2);
testInsert(avlTree, 3);
testInsert(avlTree, 4);
testInsert(avlTree, 5);
testInsert(avlTree, 8);
testInsert(avlTree, 7);
testInsert(avlTree, 9);
testInsert(avlTree, 10);
testInsert(avlTree, 6);
/* 중복 노드 삽입 */
testInsert(avlTree, 7);
/* 노드 삭제 */
// 노드를 삭제한 후 AVL 트리가 어떻게 균형을 유지하는지 살펴본다
testRemove(avlTree, 8); // 차수가 0인 노드 삭제
testRemove(avlTree, 5); // 차수가 1인 노드 삭제
testRemove(avlTree, 4); // 차수가 2인 노드 삭제
/* 노드 조회 */
const node = avlTree.search(7);
console.log('\n찾은 노드 객체:', node, ', 노드 값 = ' + node.val);

View File

@@ -0,0 +1,139 @@
/**
* File: binary_search_tree.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 이진 탐색 트리 */
class BinarySearchTree {
/* 생성자 */
constructor() {
// 빈 트리를 초기화한다
this.root = null;
}
/* 이진 트리의 루트 노드 반환 */
getRoot() {
return this.root;
}
/* 노드 탐색 */
search(num) {
let cur = this.root;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur !== null) {
// 목표 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < num) cur = cur.right;
// 목표 노드는 cur의 왼쪽 서브트리에 있다
else if (cur.val > num) cur = cur.left;
// 목표 노드를 찾았으므로 반복문을 종료한다
else break;
}
// 목표 노드를 반환한다
return cur;
}
/* 노드 삽입 */
insert(num) {
// 트리가 비어 있으면 루트 노드를 초기화한다
if (this.root === null) {
this.root = new TreeNode(num);
return;
}
let cur = this.root,
pre = null;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur !== null) {
// 중복 노드를 찾으면 바로 반환한다
if (cur.val === num) return;
pre = cur;
// 삽입 위치는 cur의 오른쪽 서브트리에 있다
if (cur.val < num) cur = cur.right;
// 삽입 위치는 cur의 왼쪽 서브트리에 있다
else cur = cur.left;
}
// 노드 삽입
const node = new TreeNode(num);
if (pre.val < num) pre.right = node;
else pre.left = node;
}
/* 노드 삭제 */
remove(num) {
// 트리가 비어 있으면 바로 반환하여 종료한다
if (this.root === null) return;
let cur = this.root,
pre = null;
// 반복하여 탐색하다 리프 노드를 지나면 종료한다
while (cur !== null) {
// 삭제할 노드를 찾았으므로 반복문을 종료한다
if (cur.val === num) break;
pre = cur;
// 삭제할 노드는 cur의 오른쪽 서브트리에 있다
if (cur.val < num) cur = cur.right;
// 삭제할 노드는 cur의 왼쪽 서브트리에 있다
else cur = cur.left;
}
// 삭제할 노드가 없으면 바로 반환한다
if (cur === null) return;
// 자식 노드 수 = 0 또는 1
if (cur.left === null || cur.right === null) {
// 자식 노드 수 = 0 / 1이면 child = null / 해당 자식 노드이다
const child = cur.left !== null ? cur.left : cur.right;
// 노드 cur를 삭제한다
if (cur !== this.root) {
if (pre.left === cur) pre.left = child;
else pre.right = child;
} else {
// 삭제할 노드가 루트 노드이면 루트 노드를 다시 지정한다
this.root = child;
}
}
// 자식 노드 수 = 2
else {
// 중위 순회에서 cur의 다음 노드를 구한다
let tmp = cur.right;
while (tmp.left !== null) {
tmp = tmp.left;
}
// 노드 tmp를 재귀적으로 삭제한다
this.remove(tmp.val);
// tmp로 cur를 덮어쓴다
cur.val = tmp.val;
}
}
}
/* 실행 코드 */
/* 이진 탐색 트리 초기화 */
const bst = new BinarySearchTree();
// 삽입 순서에 따라 서로 다른 이진 트리가 생성된다. 이 순서는 포화 이진 트리를 생성할 수 있다
const nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
for (const num of nums) {
bst.insert(num);
}
console.log('\n초기화한 이진 트리\n');
printTree(bst.getRoot());
/* 노드 탐색 */
const node = bst.search(7);
console.log('\n찾은 노드 객체: ' + node + ', 노드 값 = ' + node.val);
/* 노드 삽입 */
bst.insert(16);
console.log('\n노드 16을 삽입한 후의 이진 트리\n');
printTree(bst.getRoot());
/* 노드 삭제 */
bst.remove(1);
console.log('\n노드 1을 삭제한 후의 이진 트리\n');
printTree(bst.getRoot());
bst.remove(2);
console.log('\n노드 2를 삭제한 후의 이진 트리\n');
printTree(bst.getRoot());
bst.remove(4);
console.log('\n노드 4를 삭제한 후의 이진 트리\n');
printTree(bst.getRoot());

View File

@@ -0,0 +1,35 @@
/**
* File: binary_tree.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { TreeNode } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 이진 트리 초기화 */
// 노드 초기화
let n1 = new TreeNode(1),
n2 = new TreeNode(2),
n3 = new TreeNode(3),
n4 = new TreeNode(4),
n5 = new TreeNode(5);
// 노드 사이의 참조(포인터)를 설정한다
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
console.log('\n이진 트리 초기화\n');
printTree(n1);
/* 노드 삽입과 삭제 */
const P = new TreeNode(0);
// n1 -> n2 사이에 노드 P를 삽입한다
n1.left = P;
P.left = n2;
console.log('\n노드 P를 삽입한 후\n');
printTree(n1);
// 노드 P를 삭제한다
n1.left = n2;
console.log('\n노드 P를 삭제한 후\n');
printTree(n1);

View File

@@ -0,0 +1,34 @@
/**
* File: binary_tree_bfs.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
/* 레벨 순서 순회 */
function levelOrder(root) {
// 큐를 초기화하고 루트 노드를 넣는다
const queue = [root];
// 순회 순서를 저장할 리스트를 초기화한다
const list = [];
while (queue.length) {
let node = queue.shift(); // 큐에서 꺼낸다
list.push(node.val); // 노드 값을 저장한다
if (node.left) queue.push(node.left); // 왼쪽 자식 노드를 큐에 삽입한다
if (node.right) queue.push(node.right); // 오른쪽 자식 노드를 큐에 삽입한다
}
return list;
}
/* 실행 코드 */
/* 이진 트리 초기화 */
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화\n');
printTree(root);
/* 레벨 순서 순회 */
const list = levelOrder(root);
console.log('\n레벨 순서 순회의 노드 출력 순서 = ' + list);

View File

@@ -0,0 +1,60 @@
/**
* File: binary_tree_dfs.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { arrToTree } = require('../modules/TreeNode');
const { printTree } = require('../modules/PrintUtil');
// 순회 순서를 저장할 리스트를 초기화한다
const list = [];
/* 전위 순회 */
function preOrder(root) {
if (root === null) return;
// 방문 우선순위: 루트 노드 -> 왼쪽 서브트리 -> 오른쪽 서브트리
list.push(root.val);
preOrder(root.left);
preOrder(root.right);
}
/* 중위 순회 */
function inOrder(root) {
if (root === null) return;
// 방문 우선순위: 왼쪽 서브트리 -> 루트 노드 -> 오른쪽 서브트리
inOrder(root.left);
list.push(root.val);
inOrder(root.right);
}
/* 후위 순회 */
function postOrder(root) {
if (root === null) return;
// 방문 우선순위: 왼쪽 서브트리 -> 오른쪽 서브트리 -> 루트 노드
postOrder(root.left);
postOrder(root.right);
list.push(root.val);
}
/* 실행 코드 */
/* 이진 트리 초기화 */
// 여기서는 배열로부터 이진 트리를 바로 생성하는 함수를 사용한다
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
console.log('\n이진 트리 초기화\n');
printTree(root);
/* 전위 순회 */
list.length = 0;
preOrder(root);
console.log('\n전위 순회의 노드 출력 순서 = ' + list);
/* 중위 순회 */
list.length = 0;
inOrder(root);
console.log('\n중위 순회의 노드 출력 순서 = ' + list);
/* 후위 순회 */
list.length = 0;
postOrder(root);
console.log('\n후위 순회의 노드 출력 순서 = ' + list);

View File

@@ -0,0 +1,31 @@
/**
* File: ListNode.js
* Created Time: 2022-12-12
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 연결 리스트 노드 */
class ListNode {
val; // 노드 값
next; // 다음 노드를 가리키는 참조(포인터)
constructor(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
}
/* 리스트를 연결 리스트로 역직렬화 */
function arrToLinkedList(arr) {
const dum = new ListNode(0);
let head = dum;
for (const val of arr) {
head.next = new ListNode(val);
head = head.next;
}
return dum.next;
}
module.exports = {
ListNode,
arrToLinkedList,
};

View File

@@ -0,0 +1,86 @@
/**
* File: PrintUtil.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
const { arrToTree } = require('./TreeNode');
/* 연결 리스트 출력 */
function printLinkedList(head) {
let list = [];
while (head !== null) {
list.push(head.val.toString());
head = head.next;
}
console.log(list.join(' -> '));
}
function Trunk(prev, str) {
this.prev = prev;
this.str = str;
}
/**
* 이진 트리 출력
* 이 트리 출력 코드는 TECHIE DELIGHT에서 가져왔다
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
function printTree(root) {
printTree(root, null, false);
}
/* 이진 트리 출력 */
function printTree(root, prev, isRight) {
if (root === null) {
return;
}
let prev_str = ' ';
let trunk = new Trunk(prev, prev_str);
printTree(root.right, trunk, true);
if (!prev) {
trunk.str = '———';
} else if (isRight) {
trunk.str = '/———';
prev_str = ' |';
} else {
trunk.str = '\\———';
prev.str = prev_str;
}
showTrunks(trunk);
console.log(' ' + root.val);
if (prev) {
prev.str = prev_str;
}
trunk.str = ' |';
printTree(root.left, trunk, false);
}
function showTrunks(p) {
if (!p) {
return;
}
showTrunks(p.prev);
process.stdout.write(p.str);
}
/* 힙 출력 */
function printHeap(arr) {
console.log('힙의 배열 표현:');
console.log(arr);
console.log('힙의 트리 표현:');
printTree(arrToTree(arr));
}
module.exports = {
printLinkedList,
printTree,
printHeap,
};

View File

@@ -0,0 +1,35 @@
/**
* File: TreeNode.js
* Created Time: 2022-12-04
* Author: IsChristina (christinaxia77@foxmail.com)
*/
/* 이진 트리 노드 */
class TreeNode {
val; // 노드 값
left; // 왼쪽 자식 노드 포인터
right; // 오른쪽 자식 노드 포인터
height; //노드 높이
constructor(val, left, right, height) {
this.val = val === undefined ? 0 : val;
this.left = left === undefined ? null : left;
this.right = right === undefined ? null : right;
this.height = height === undefined ? 0 : height;
}
}
/* 배열을 역직렬화하여 이진 트리로 변환한다 */
function arrToTree(arr, i = 0) {
if (i < 0 || i >= arr.length || arr[i] === null) {
return null;
}
let root = new TreeNode(arr[i]);
root.left = arrToTree(arr, 2 * i + 1);
root.right = arrToTree(arr, 2 * i + 2);
return root;
}
module.exports = {
TreeNode,
arrToTree,
};

View File

@@ -0,0 +1,35 @@
/**
* File: Vertex.js
* Created Time: 2023-02-15
* Author: Zhuo Qinyue (1403450829@qq.com)
*/
/* 정점 클래스 */
class Vertex {
val;
constructor(val) {
this.val = val;
}
/* 값의 리스트 vals를 입력받아 정점 리스트 vets 반환 */
static valsToVets(vals) {
const vets = [];
for (let i = 0; i < vals.length; i++) {
vets[i] = new Vertex(vals[i]);
}
return vets;
}
/* 정점 리스트 vets를 입력받아 값의 리스트 vals 반환 */
static vetsToVals(vets) {
const vals = [];
for (const vet of vets) {
vals.push(vet.val);
}
return vals;
}
}
module.exports = {
Vertex,
};

View File

@@ -0,0 +1,63 @@
import { bold, brightRed } from 'jsr:@std/fmt/colors';
import { expandGlob } from 'jsr:@std/fs';
import { relative, resolve } from 'jsr:@std/path';
/**
* @typedef {import('jsr:@std/fs').WalkEntry} WalkEntry
* @type {WalkEntry[]}
*/
const entries = [];
for await (const entry of expandGlob(
resolve(import.meta.dirname, './chapter_*/*.js')
)) {
entries.push(entry);
}
/** @type {{ status: Promise<Deno.CommandStatus>; stderr: ReadableStream<Uint8Array>; }[]} */
const processes = [];
for (const file of entries) {
const execute = new Deno.Command('node', {
args: [relative(import.meta.dirname, file.path)],
cwd: import.meta.dirname,
stdin: 'piped',
stdout: 'piped',
stderr: 'piped',
});
const process = execute.spawn();
processes.push({ status: process.status, stderr: process.stderr });
}
const results = await Promise.all(
processes.map(async (item) => {
const status = await item.status;
return { status, stderr: item.stderr };
})
);
/** @type {ReadableStream<Uint8Array>[]} */
const errors = [];
for (const result of results) {
if (!result.status.success) {
errors.push(result.stderr);
}
}
console.log(`파일 ${entries.length}개를 테스트했다`);
console.log(`파일 ${errors.length}개에서 예외가 발생했다`);
if (errors.length) {
console.log();
for (const error of errors) {
const reader = error.getReader();
const { value } = await reader.read();
const decoder = new TextDecoder();
console.log(`${bold(brightRed('오류'))}: ${decoder.decode(value)}`);
}
throw new Error('테스트에 실패했다');
}