mirror of
https://github.com/krahets/hello-algo.git
synced 2026-08-11 19:30:59 +00:00
Translate all code to English (#1836)
* Review the EN heading format. * Fix pythontutor headings. * Fix pythontutor headings. * bug fixes * Fix headings in **/summary.md * Revisit the CN-to-EN translation for Python code using Claude-4.5 * Revisit the CN-to-EN translation for Java code using Claude-4.5 * Revisit the CN-to-EN translation for Cpp code using Claude-4.5. * Fix the dictionary. * Fix cpp code translation for the multipart strings. * Translate Go code to English. * Update workflows to test EN code. * Add EN translation for C. * Add EN translation for CSharp. * Add EN translation for Swift. * Trigger the CI check. * Revert. * Update en/hash_map.md * Add the EN version of Dart code. * Add the EN version of Kotlin code. * Add missing code files. * Add the EN version of JavaScript code. * Add the EN version of TypeScript code. * Fix the workflows. * Add the EN version of Ruby code. * Add the EN version of Rust code. * Update the CI check for the English version code. * Update Python CI check. * Fix cmakelists for en/C code. * Fix Ruby comments
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
package-lock.json
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"tabWidth": 4,
|
||||
"useTabs": false,
|
||||
"semi": true,
|
||||
"singleQuote": true
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
/**
|
||||
* File: array.ts
|
||||
* Created Time: 2022-12-04
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Random access to element */
|
||||
function randomAccess(nums: number[]): number {
|
||||
// Randomly select a number in the interval [0, nums.length)
|
||||
const random_index = Math.floor(Math.random() * nums.length);
|
||||
// Retrieve and return the random element
|
||||
const random_num = nums[random_index];
|
||||
return random_num;
|
||||
}
|
||||
|
||||
/* Extend array length */
|
||||
// Note: TypeScript's Array is dynamic array, can be directly expanded
|
||||
// For learning purposes, this function treats Array as fixed-length array
|
||||
function extend(nums: number[], enlarge: number): number[] {
|
||||
// Initialize an array with extended length
|
||||
const res = new Array(nums.length + enlarge).fill(0);
|
||||
// Copy all elements from the original array to the new array
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
res[i] = nums[i];
|
||||
}
|
||||
// Return the extended new array
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Insert element num at index index in the array */
|
||||
function insert(nums: number[], num: number, index: number): void {
|
||||
// Move all elements at and after index index backward by one position
|
||||
for (let i = nums.length - 1; i > index; i--) {
|
||||
nums[i] = nums[i - 1];
|
||||
}
|
||||
// Assign num to the element at index index
|
||||
nums[index] = num;
|
||||
}
|
||||
|
||||
/* Remove the element at index index */
|
||||
function remove(nums: number[], index: number): void {
|
||||
// Move all elements after index index forward by one position
|
||||
for (let i = index; i < nums.length - 1; i++) {
|
||||
nums[i] = nums[i + 1];
|
||||
}
|
||||
}
|
||||
|
||||
/* Traverse array */
|
||||
function traverse(nums: number[]): void {
|
||||
let count = 0;
|
||||
// Traverse array by index
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
// Direct traversal of array elements
|
||||
for (const num of nums) {
|
||||
count += num;
|
||||
}
|
||||
}
|
||||
|
||||
/* Find the specified element in the array */
|
||||
function find(nums: number[], target: number): number {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
if (nums[i] === target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize array */
|
||||
const arr: number[] = new Array(5).fill(0);
|
||||
console.log('Array arr =', arr);
|
||||
let nums: number[] = [1, 3, 2, 5, 4];
|
||||
console.log('Array nums =', nums);
|
||||
|
||||
/* Insert element */
|
||||
let random_num = randomAccess(nums);
|
||||
console.log('Get random element in nums', random_num);
|
||||
|
||||
/* Traverse array */
|
||||
nums = extend(nums, 3);
|
||||
console.log('Extend array length to 8, get nums =', nums);
|
||||
|
||||
/* Insert element */
|
||||
insert(nums, 6, 3);
|
||||
console.log('Insert number 6 at index 3, get nums =', nums);
|
||||
|
||||
/* Remove element */
|
||||
remove(nums, 2);
|
||||
console.log('Remove element at index 2, get nums =', nums);
|
||||
|
||||
/* Traverse array */
|
||||
traverse(nums);
|
||||
|
||||
/* Find element */
|
||||
let index = find(nums, 3);
|
||||
console.log('Find element 3 in nums, get index =', index);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,86 @@
|
||||
/**
|
||||
* File: linked_list.ts
|
||||
* Created Time: 2022-12-10
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { ListNode } from '../modules/ListNode';
|
||||
import { printLinkedList } from '../modules/PrintUtil';
|
||||
|
||||
/* Insert node P after node n0 in the linked list */
|
||||
function insert(n0: ListNode, P: ListNode): void {
|
||||
const n1 = n0.next;
|
||||
P.next = n1;
|
||||
n0.next = P;
|
||||
}
|
||||
|
||||
/* Remove the first node after node n0 in the linked list */
|
||||
function remove(n0: ListNode): void {
|
||||
if (!n0.next) {
|
||||
return;
|
||||
}
|
||||
// n0 -> P -> n1
|
||||
const P = n0.next;
|
||||
const n1 = P.next;
|
||||
n0.next = n1;
|
||||
}
|
||||
|
||||
/* Access the node at index index in the linked list */
|
||||
function access(head: ListNode | null, index: number): ListNode | null {
|
||||
for (let i = 0; i < index; i++) {
|
||||
if (!head) {
|
||||
return null;
|
||||
}
|
||||
head = head.next;
|
||||
}
|
||||
return head;
|
||||
}
|
||||
|
||||
/* Find the first node with value target in the linked list */
|
||||
function find(head: ListNode | null, target: number): number {
|
||||
let index = 0;
|
||||
while (head !== null) {
|
||||
if (head.val === target) {
|
||||
return index;
|
||||
}
|
||||
head = head.next;
|
||||
index += 1;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize linked list */
|
||||
// Initialize each node
|
||||
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);
|
||||
// Build references between nodes
|
||||
n0.next = n1;
|
||||
n1.next = n2;
|
||||
n2.next = n3;
|
||||
n3.next = n4;
|
||||
console.log('Initialized linked list is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Insert node */
|
||||
insert(n0, new ListNode(0));
|
||||
console.log('Linked list after inserting node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Remove node */
|
||||
remove(n0);
|
||||
console.log('Linked list after removing node is');
|
||||
printLinkedList(n0);
|
||||
|
||||
/* Access node */
|
||||
const node = access(n0, 3);
|
||||
console.log(`Value of node at index 3 in linked list = ${node?.val}`);
|
||||
|
||||
/* Search node */
|
||||
const index = find(n0, 2);
|
||||
console.log(`Index of node with value 2 in linked list = ${index}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: list.ts
|
||||
* Created Time: 2022-12-10
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Initialize list */
|
||||
const nums: number[] = [1, 3, 2, 5, 4];
|
||||
console.log(`List nums = ${nums}`);
|
||||
|
||||
/* Update element */
|
||||
const num: number = nums[1];
|
||||
console.log(`Access element at index 1, get num = ${num}`);
|
||||
|
||||
/* Add elements at the end */
|
||||
nums[1] = 0;
|
||||
console.log(`Update element at index 1 to 0, get nums = ${nums}`);
|
||||
|
||||
/* Remove element */
|
||||
nums.length = 0;
|
||||
console.log(`After clearing list, nums = ${nums}`);
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
nums.push(1);
|
||||
nums.push(3);
|
||||
nums.push(2);
|
||||
nums.push(5);
|
||||
nums.push(4);
|
||||
console.log(`After adding elements, nums = ${nums}`);
|
||||
|
||||
/* Sort list */
|
||||
nums.splice(3, 0, 6);
|
||||
console.log(`Insert number 6 at index 3, get nums = ${nums}`);
|
||||
|
||||
/* Remove element */
|
||||
nums.splice(3, 1);
|
||||
console.log(`Delete element at index 3, get nums = ${nums}`);
|
||||
|
||||
/* Traverse list by index */
|
||||
let count = 0;
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count += nums[i];
|
||||
}
|
||||
/* Directly traverse list elements */
|
||||
count = 0;
|
||||
for (const x of nums) {
|
||||
count += x;
|
||||
}
|
||||
|
||||
/* Concatenate two lists */
|
||||
const nums1: number[] = [6, 8, 7, 10, 9];
|
||||
nums.push(...nums1);
|
||||
console.log(`After concatenating list nums1 to nums, get nums = ${nums}`);
|
||||
|
||||
/* Sort list */
|
||||
nums.sort((a, b) => a - b);
|
||||
console.log(`After sorting list, nums = ${nums}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* File: my_list.ts
|
||||
* Created Time: 2022-12-11
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* List class */
|
||||
class MyList {
|
||||
private arr: Array<number>; // Array (stores list elements)
|
||||
private _capacity: number = 10; // List capacity
|
||||
private _size: number = 0; // List length (current number of elements)
|
||||
private extendRatio: number = 2; // Multiple by which the list capacity is extended each time
|
||||
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.arr = new Array(this._capacity);
|
||||
}
|
||||
|
||||
/* Get list length (current number of elements) */
|
||||
public size(): number {
|
||||
return this._size;
|
||||
}
|
||||
|
||||
/* Get list capacity */
|
||||
public capacity(): number {
|
||||
return this._capacity;
|
||||
}
|
||||
|
||||
/* Update element */
|
||||
public get(index: number): number {
|
||||
// If the index is out of bounds, throw an exception, as below
|
||||
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
|
||||
return this.arr[index];
|
||||
}
|
||||
|
||||
/* Add elements at the end */
|
||||
public set(index: number, num: number): void {
|
||||
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
|
||||
this.arr[index] = num;
|
||||
}
|
||||
|
||||
/* Direct traversal of list elements */
|
||||
public add(num: number): void {
|
||||
// If length equals capacity, need to expand
|
||||
if (this._size === this._capacity) this.extendCapacity();
|
||||
// Add new element to end of list
|
||||
this.arr[this._size] = num;
|
||||
this._size++;
|
||||
}
|
||||
|
||||
/* Sort list */
|
||||
public insert(index: number, num: number): void {
|
||||
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
|
||||
// When the number of elements exceeds capacity, trigger the extension mechanism
|
||||
if (this._size === this._capacity) {
|
||||
this.extendCapacity();
|
||||
}
|
||||
// Move all elements after index index forward by one position
|
||||
for (let j = this._size - 1; j >= index; j--) {
|
||||
this.arr[j + 1] = this.arr[j];
|
||||
}
|
||||
// Update the number of elements
|
||||
this.arr[index] = num;
|
||||
this._size++;
|
||||
}
|
||||
|
||||
/* Remove element */
|
||||
public remove(index: number): number {
|
||||
if (index < 0 || index >= this._size) throw new Error('Index out of bounds');
|
||||
let num = this.arr[index];
|
||||
// Move all elements after index forward by one position
|
||||
for (let j = index; j < this._size - 1; j++) {
|
||||
this.arr[j] = this.arr[j + 1];
|
||||
}
|
||||
// Update the number of elements
|
||||
this._size--;
|
||||
// Return the removed element
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
public extendCapacity(): void {
|
||||
// Create new array of length size and copy original array to new array
|
||||
this.arr = this.arr.concat(
|
||||
new Array(this.capacity() * (this.extendRatio - 1))
|
||||
);
|
||||
// Add elements at the end
|
||||
this._capacity = this.arr.length;
|
||||
}
|
||||
|
||||
/* Convert list to array */
|
||||
public toArray(): number[] {
|
||||
let size = this.size();
|
||||
// Elements enqueue
|
||||
const arr = new Array(size);
|
||||
for (let i = 0; i < size; i++) {
|
||||
arr[i] = this.get(i);
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize list */
|
||||
const nums = new MyList();
|
||||
/* Direct traversal of list elements */
|
||||
nums.add(1);
|
||||
nums.add(3);
|
||||
nums.add(2);
|
||||
nums.add(5);
|
||||
nums.add(4);
|
||||
console.log(
|
||||
`List nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}`
|
||||
);
|
||||
|
||||
/* Sort list */
|
||||
nums.insert(3, 6);
|
||||
console.log(`Insert number 6 at index 3, get nums = ${nums.toArray()}`);
|
||||
|
||||
/* Remove element */
|
||||
nums.remove(3);
|
||||
console.log(`Delete element at index 3, get nums = ${nums.toArray()}`);
|
||||
|
||||
/* Update element */
|
||||
const num = nums.get(1);
|
||||
console.log(`Access element at index 1, get num = ${num}`);
|
||||
|
||||
/* Add elements at the end */
|
||||
nums.set(1, 0);
|
||||
console.log(`Update element at index 1 to 0, get nums = ${nums.toArray()}`);
|
||||
|
||||
/* Test capacity expansion mechanism */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
|
||||
nums.add(i);
|
||||
}
|
||||
console.log(
|
||||
`After expansion, list nums = ${nums.toArray()}, capacity = ${nums.capacity()}, length = ${nums.size()}`
|
||||
);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* File: n_queens.ts
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: N queens */
|
||||
function backtrack(
|
||||
row: number,
|
||||
n: number,
|
||||
state: string[][],
|
||||
res: string[][][],
|
||||
cols: boolean[],
|
||||
diags1: boolean[],
|
||||
diags2: boolean[]
|
||||
): void {
|
||||
// When all rows are placed, record the solution
|
||||
if (row === n) {
|
||||
res.push(state.map((row) => row.slice()));
|
||||
return;
|
||||
}
|
||||
// Traverse all columns
|
||||
for (let col = 0; col < n; col++) {
|
||||
// Calculate the main diagonal and anti-diagonal corresponding to this cell
|
||||
const diag1 = row - col + n - 1;
|
||||
const diag2 = row + col;
|
||||
// Pruning: do not allow queens to exist in the column, main diagonal, and anti-diagonal of this cell
|
||||
if (!cols[col] && !diags1[diag1] && !diags2[diag2]) {
|
||||
// Attempt: place the queen in this cell
|
||||
state[row][col] = 'Q';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = true;
|
||||
// Place the next row
|
||||
backtrack(row + 1, n, state, res, cols, diags1, diags2);
|
||||
// Backtrack: restore this cell to an empty cell
|
||||
state[row][col] = '#';
|
||||
cols[col] = diags1[diag1] = diags2[diag2] = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve N queens */
|
||||
function nQueens(n: number): string[][][] {
|
||||
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
|
||||
const state = Array.from({ length: n }, () => Array(n).fill('#'));
|
||||
const cols = Array(n).fill(false); // Record whether there is a queen in the column
|
||||
const diags1 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the main diagonal
|
||||
const diags2 = Array(2 * n - 1).fill(false); // Record whether there is a queen on the anti-diagonal
|
||||
const res: string[][][] = [];
|
||||
|
||||
backtrack(0, n, state, res, cols, diags1, diags2);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const n = 4;
|
||||
const res = nQueens(n);
|
||||
|
||||
console.log(`Input board size is ${n}`);
|
||||
console.log(`Total queen placement solutions: ${res.length}`);
|
||||
res.forEach((state) => {
|
||||
console.log('--------------------');
|
||||
state.forEach((row) => console.log(row));
|
||||
});
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: permutations_i.ts
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations I */
|
||||
function backtrack(
|
||||
state: number[],
|
||||
choices: number[],
|
||||
selected: boolean[],
|
||||
res: number[][]
|
||||
): void {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements
|
||||
if (!selected[i]) {
|
||||
// Attempt: make choice, update state
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* Permutations I */
|
||||
function permutationsI(nums: number[]): number[][] {
|
||||
const res: number[][] = [];
|
||||
backtrack([], nums, Array(nums.length).fill(false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const nums: number[] = [1, 2, 3];
|
||||
const res: number[][] = permutationsI(nums);
|
||||
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}`);
|
||||
console.log(`All permutations res = ${JSON.stringify(res)}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: permutations_ii.ts
|
||||
* Created Time: 2023-05-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Permutations II */
|
||||
function backtrack(
|
||||
state: number[],
|
||||
choices: number[],
|
||||
selected: boolean[],
|
||||
res: number[][]
|
||||
): void {
|
||||
// When the state length equals the number of elements, record the solution
|
||||
if (state.length === choices.length) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
const duplicated = new Set();
|
||||
choices.forEach((choice, i) => {
|
||||
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
|
||||
if (!selected[i] && !duplicated.has(choice)) {
|
||||
// Attempt: make choice, update state
|
||||
duplicated.add(choice); // Record the selected element value
|
||||
selected[i] = true;
|
||||
state.push(choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, choices, selected, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
selected[i] = false;
|
||||
state.pop();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/* Permutations II */
|
||||
function permutationsII(nums: number[]): number[][] {
|
||||
const res: number[][] = [];
|
||||
backtrack([], nums, Array(nums.length).fill(false), res);
|
||||
return res;
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const nums: number[] = [1, 2, 2];
|
||||
const res: number[][] = permutationsII(nums);
|
||||
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}`);
|
||||
console.log(`All permutations res = ${JSON.stringify(res)}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: preorder_traversal_i_compact.ts
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Preorder traversal: Example 1 */
|
||||
function preOrder(root: TreeNode | null, res: TreeNode[]): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
res.push(root);
|
||||
}
|
||||
preOrder(root.left, res);
|
||||
preOrder(root.right, res);
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
const res: TreeNode[] = [];
|
||||
preOrder(root, res);
|
||||
|
||||
console.log('\nOutput all nodes with value 7');
|
||||
console.log(res.map((node) => node.val));
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* File: preorder_traversal_ii_compact.ts
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Preorder traversal: Example 2 */
|
||||
function preOrder(
|
||||
root: TreeNode | null,
|
||||
path: TreeNode[],
|
||||
res: TreeNode[][]
|
||||
): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// Backtrack
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
const path: TreeNode[] = [];
|
||||
const res: TreeNode[][] = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,48 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_compact.ts
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Preorder traversal: Example 3 */
|
||||
function preOrder(
|
||||
root: TreeNode | null,
|
||||
path: TreeNode[],
|
||||
res: TreeNode[][]
|
||||
): void {
|
||||
// Pruning
|
||||
if (root === null || root.val === 3) {
|
||||
return;
|
||||
}
|
||||
// Attempt
|
||||
path.push(root);
|
||||
if (root.val === 7) {
|
||||
// Record solution
|
||||
res.push([...path]);
|
||||
}
|
||||
preOrder(root.left, path, res);
|
||||
preOrder(root.right, path, res);
|
||||
// Backtrack
|
||||
path.pop();
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Preorder traversal
|
||||
const path: TreeNode[] = [];
|
||||
const res: TreeNode[][] = [];
|
||||
preOrder(root, path, res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, paths do not include nodes with value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* File: preorder_traversal_iii_template.ts
|
||||
* Created Time: 2023-05-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Check if the current state is a solution */
|
||||
function isSolution(state: TreeNode[]): boolean {
|
||||
return state && state[state.length - 1]?.val === 7;
|
||||
}
|
||||
|
||||
/* Record solution */
|
||||
function recordSolution(state: TreeNode[], res: TreeNode[][]): void {
|
||||
res.push([...state]);
|
||||
}
|
||||
|
||||
/* Check if the choice is valid under the current state */
|
||||
function isValid(state: TreeNode[], choice: TreeNode): boolean {
|
||||
return choice !== null && choice.val !== 3;
|
||||
}
|
||||
|
||||
/* Update state */
|
||||
function makeChoice(state: TreeNode[], choice: TreeNode): void {
|
||||
state.push(choice);
|
||||
}
|
||||
|
||||
/* Restore state */
|
||||
function undoChoice(state: TreeNode[]): void {
|
||||
state.pop();
|
||||
}
|
||||
|
||||
/* Backtracking algorithm: Example 3 */
|
||||
function backtrack(
|
||||
state: TreeNode[],
|
||||
choices: TreeNode[],
|
||||
res: TreeNode[][]
|
||||
): void {
|
||||
// Check if it is a solution
|
||||
if (isSolution(state)) {
|
||||
// Record solution
|
||||
recordSolution(state, res);
|
||||
}
|
||||
// Traverse all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: check if the choice is valid
|
||||
if (isValid(state, choice)) {
|
||||
// Attempt: make choice, update state
|
||||
makeChoice(state, choice);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, [choice.left, choice.right], res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
undoChoice(state);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Driver Code
|
||||
const root = arrToTree([1, 7, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree');
|
||||
printTree(root);
|
||||
|
||||
// Backtracking algorithm
|
||||
const res: TreeNode[][] = [];
|
||||
backtrack([], [root], res);
|
||||
|
||||
console.log('\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3');
|
||||
res.forEach((path) => {
|
||||
console.log(path.map((node) => node.val));
|
||||
});
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: subset_sum_i.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
function backtrack(
|
||||
state: number[],
|
||||
target: number,
|
||||
choices: number[],
|
||||
start: number,
|
||||
res: number[][]
|
||||
): void {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I */
|
||||
function subsetSumI(nums: number[], target: number): number[][] {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumI(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: subset_sum_i_naive.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum I */
|
||||
function backtrack(
|
||||
state: number[],
|
||||
target: number,
|
||||
total: number,
|
||||
choices: number[],
|
||||
res: number[][]
|
||||
): void {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (total === target) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
for (let i = 0; i < choices.length; i++) {
|
||||
// Pruning: if the subset sum exceeds target, skip this choice
|
||||
if (total + choices[i] > target) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update element sum total
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target, total + choices[i], choices, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum I (including duplicate subsets) */
|
||||
function subsetSumINaive(nums: number[], target: number): number[][] {
|
||||
const state = []; // State (subset)
|
||||
const total = 0; // Subset sum
|
||||
const res = []; // Result list (subset list)
|
||||
backtrack(state, target, total, nums, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [3, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumINaive(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
console.log('Please note that this method outputs results containing duplicate sets');
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* File: subset_sum_ii.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking algorithm: Subset sum II */
|
||||
function backtrack(
|
||||
state: number[],
|
||||
target: number,
|
||||
choices: number[],
|
||||
start: number,
|
||||
res: number[][]
|
||||
): void {
|
||||
// When the subset sum equals target, record the solution
|
||||
if (target === 0) {
|
||||
res.push([...state]);
|
||||
return;
|
||||
}
|
||||
// Traverse all choices
|
||||
// Pruning 2: start traversing from start to avoid generating duplicate subsets
|
||||
// Pruning 3: start traversing from start to avoid repeatedly selecting the same element
|
||||
for (let i = start; i < choices.length; i++) {
|
||||
// Pruning 1: if the subset sum exceeds target, end the loop directly
|
||||
// This is because the array is sorted, and later elements are larger, so the subset sum will definitely exceed target
|
||||
if (target - choices[i] < 0) {
|
||||
break;
|
||||
}
|
||||
// Pruning 4: if this element equals the left element, it means this search branch is duplicate, skip it directly
|
||||
if (i > start && choices[i] === choices[i - 1]) {
|
||||
continue;
|
||||
}
|
||||
// Attempt: make choice, update target, start
|
||||
state.push(choices[i]);
|
||||
// Proceed to the next round of selection
|
||||
backtrack(state, target - choices[i], choices, i + 1, res);
|
||||
// Backtrack: undo choice, restore to previous state
|
||||
state.pop();
|
||||
}
|
||||
}
|
||||
|
||||
/* Solve subset sum II */
|
||||
function subsetSumII(nums: number[], target: number): number[][] {
|
||||
const state = []; // State (subset)
|
||||
nums.sort((a, b) => a - b); // Sort nums
|
||||
const start = 0; // Start point for traversal
|
||||
const res = []; // Result list (subset list)
|
||||
backtrack(state, target, nums, start, res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [4, 4, 5];
|
||||
const target = 9;
|
||||
const res = subsetSumII(nums, target);
|
||||
console.log(`Input array nums = ${JSON.stringify(nums)}, target = ${target}`);
|
||||
console.log(`All subsets with sum equal to ${target} res = ${JSON.stringify(res)}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* File: iteration.ts
|
||||
* Created Time: 2023-08-28
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* for loop */
|
||||
function forLoop(n: number): number {
|
||||
let res = 0;
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
for (let i = 1; i <= n; i++) {
|
||||
res += i;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while loop */
|
||||
function whileLoop(n: number): number {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 2, ..., n-1, n
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
i++; // Update condition variable
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* while loop (two updates) */
|
||||
function whileLoopII(n: number): number {
|
||||
let res = 0;
|
||||
let i = 1; // Initialize condition variable
|
||||
// Sum 1, 4, 10, ...
|
||||
while (i <= n) {
|
||||
res += i;
|
||||
// Update condition variable
|
||||
i++;
|
||||
i *= 2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Nested for loop */
|
||||
function nestedForLoop(n: number): string {
|
||||
let res = '';
|
||||
// Loop i = 1, 2, ..., n-1, n
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Loop j = 1, 2, ..., n-1, n
|
||||
for (let j = 1; j <= n; j++) {
|
||||
res += `(${i}, ${j}), `;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 5;
|
||||
let res: number;
|
||||
|
||||
res = forLoop(n);
|
||||
console.log(`For loop sum result res = ${res}`);
|
||||
|
||||
res = whileLoop(n);
|
||||
console.log(`While loop sum result res = ${res}`);
|
||||
|
||||
res = whileLoopII(n);
|
||||
console.log(`While loop (two updates) sum result res = ${res}`);
|
||||
|
||||
const resStr = nestedForLoop(n);
|
||||
console.log(`Nested for loop traversal result ${resStr}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,70 @@
|
||||
/**
|
||||
* File: recursion.ts
|
||||
* Created Time: 2023-08-28
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Recursion */
|
||||
function recur(n: number): number {
|
||||
// Termination condition
|
||||
if (n === 1) return 1;
|
||||
// Recurse: recursive call
|
||||
const res = recur(n - 1);
|
||||
// Return: return result
|
||||
return n + res;
|
||||
}
|
||||
|
||||
/* Simulate recursion using iteration */
|
||||
function forLoopRecur(n: number): number {
|
||||
// Use an explicit stack to simulate the system call stack
|
||||
const stack: number[] = [];
|
||||
let res: number = 0;
|
||||
// Recurse: recursive call
|
||||
for (let i = n; i > 0; i--) {
|
||||
// Simulate "recurse" with "push"
|
||||
stack.push(i);
|
||||
}
|
||||
// Return: return result
|
||||
while (stack.length) {
|
||||
// Simulate "return" with "pop"
|
||||
res += stack.pop();
|
||||
}
|
||||
// res = 1+2+3+...+n
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Tail recursion */
|
||||
function tailRecur(n: number, res: number): number {
|
||||
// Termination condition
|
||||
if (n === 0) return res;
|
||||
// Tail recursive call
|
||||
return tailRecur(n - 1, res + n);
|
||||
}
|
||||
|
||||
/* Fibonacci sequence: recursion */
|
||||
function fib(n: number): number {
|
||||
// Termination condition f(1) = 0, f(2) = 1
|
||||
if (n === 1 || n === 2) return n - 1;
|
||||
// Recursive call f(n) = f(n-1) + f(n-2)
|
||||
const res = fib(n - 1) + fib(n - 2);
|
||||
// Return result f(n)
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 5;
|
||||
let res: number;
|
||||
|
||||
res = recur(n);
|
||||
console.log(`Recursion sum result res = ${res}`);
|
||||
|
||||
res = forLoopRecur(n);
|
||||
console.log(`Using iteration to simulate recursion sum result res = ${res}`);
|
||||
|
||||
res = tailRecur(n, 0);
|
||||
console.log(`Tail recursion sum result res = ${res}`);
|
||||
|
||||
res = fib(n);
|
||||
console.log(`The ${n}th Fibonacci number is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* File: space_complexity.ts
|
||||
* Created Time: 2023-02-05
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { ListNode } from '../modules/ListNode';
|
||||
import { TreeNode } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Function */
|
||||
function constFunc(): number {
|
||||
// Perform some operations
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Constant order */
|
||||
function constant(n: number): void {
|
||||
// Constants, variables, objects occupy O(1) space
|
||||
const a = 0;
|
||||
const b = 0;
|
||||
const nums = new Array(10000);
|
||||
const node = new ListNode(0);
|
||||
// Variables in the loop occupy O(1) space
|
||||
for (let i = 0; i < n; i++) {
|
||||
const c = 0;
|
||||
}
|
||||
// Functions in the loop occupy O(1) space
|
||||
for (let i = 0; i < n; i++) {
|
||||
constFunc();
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
function linear(n: number): void {
|
||||
// Array of length n uses O(n) space
|
||||
const nums = new Array(n);
|
||||
// A list of length n occupies O(n) space
|
||||
const nodes: ListNode[] = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
nodes.push(new ListNode(i));
|
||||
}
|
||||
// A hash table of length n occupies O(n) space
|
||||
const map = new Map();
|
||||
for (let i = 0; i < n; i++) {
|
||||
map.set(i, i.toString());
|
||||
}
|
||||
}
|
||||
|
||||
/* Linear order (recursive implementation) */
|
||||
function linearRecur(n: number): void {
|
||||
console.log(`Recursion n = ${n}`);
|
||||
if (n === 1) return;
|
||||
linearRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
function quadratic(n: number): void {
|
||||
// Matrix uses O(n^2) space
|
||||
const numMatrix = Array(n)
|
||||
.fill(null)
|
||||
.map(() => Array(n).fill(null));
|
||||
// 2D list uses O(n^2) space
|
||||
const numList = [];
|
||||
for (let i = 0; i < n; i++) {
|
||||
const tmp = [];
|
||||
for (let j = 0; j < n; j++) {
|
||||
tmp.push(0);
|
||||
}
|
||||
numList.push(tmp);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quadratic order (recursive implementation) */
|
||||
function quadraticRecur(n: number): number {
|
||||
if (n <= 0) return 0;
|
||||
const nums = new Array(n);
|
||||
console.log(`In recursion n = ${n}, nums length = ${nums.length}`);
|
||||
return quadraticRecur(n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
function buildTree(n: number): TreeNode | null {
|
||||
if (n === 0) return null;
|
||||
const root = new TreeNode(0);
|
||||
root.left = buildTree(n - 1);
|
||||
root.right = buildTree(n - 1);
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 5;
|
||||
// Constant order
|
||||
constant(n);
|
||||
// Linear order
|
||||
linear(n);
|
||||
linearRecur(n);
|
||||
// Exponential order
|
||||
quadratic(n);
|
||||
quadraticRecur(n);
|
||||
// Exponential order
|
||||
const root = buildTree(n);
|
||||
printTree(root);
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* File: time_complexity.ts
|
||||
* Created Time: 2023-01-02
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Constant order */
|
||||
function constant(n: number): number {
|
||||
let count = 0;
|
||||
const size = 100000;
|
||||
for (let i = 0; i < size; i++) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order */
|
||||
function linear(n: number): number {
|
||||
let count = 0;
|
||||
for (let i = 0; i < n; i++) count++;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Linear order (traversing array) */
|
||||
function arrayTraversal(nums: number[]): number {
|
||||
let count = 0;
|
||||
// Number of iterations is proportional to the array length
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order */
|
||||
function quadratic(n: number): number {
|
||||
let count = 0;
|
||||
// Number of iterations is quadratically related to the data size n
|
||||
for (let i = 0; i < n; i++) {
|
||||
for (let j = 0; j < n; j++) {
|
||||
count++;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Quadratic order (bubble sort) */
|
||||
function bubbleSort(nums: number[]): number {
|
||||
let count = 0; // Counter
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
count += 3; // Element swap includes 3 unit operations
|
||||
}
|
||||
}
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Exponential order (loop implementation) */
|
||||
function exponential(n: number): number {
|
||||
let count = 0,
|
||||
base = 1;
|
||||
// Cells divide into two every round, forming sequence 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;
|
||||
}
|
||||
|
||||
/* Exponential order (recursive implementation) */
|
||||
function expRecur(n: number): number {
|
||||
if (n === 1) return 1;
|
||||
return expRecur(n - 1) + expRecur(n - 1) + 1;
|
||||
}
|
||||
|
||||
/* Logarithmic order (loop implementation) */
|
||||
function logarithmic(n: number): number {
|
||||
let count = 0;
|
||||
while (n > 1) {
|
||||
n = n / 2;
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Logarithmic order (recursive implementation) */
|
||||
function logRecur(n: number): number {
|
||||
if (n <= 1) return 0;
|
||||
return logRecur(n / 2) + 1;
|
||||
}
|
||||
|
||||
/* Linearithmic order */
|
||||
function linearLogRecur(n: number): number {
|
||||
if (n <= 1) return 1;
|
||||
let count = linearLogRecur(n / 2) + linearLogRecur(n / 2);
|
||||
for (let i = 0; i < n; i++) {
|
||||
count++;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Factorial order (recursive implementation) */
|
||||
function factorialRecur(n: number): number {
|
||||
if (n === 0) return 1;
|
||||
let count = 0;
|
||||
// Split from 1 into n
|
||||
for (let i = 0; i < n; i++) {
|
||||
count += factorialRecur(n - 1);
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// You can modify n to run and observe the trend of the number of operations for various complexities
|
||||
const n = 8;
|
||||
console.log('Input data size n = ' + n);
|
||||
|
||||
let count = constant(n);
|
||||
console.log('Constant order operation count = ' + count);
|
||||
|
||||
count = linear(n);
|
||||
console.log('Linear order operation count = ' + count);
|
||||
count = arrayTraversal(new Array(n));
|
||||
console.log('Linear order (array traversal) operation count = ' + count);
|
||||
|
||||
count = quadratic(n);
|
||||
console.log('Quadratic order operation count = ' + count);
|
||||
var 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('Quadratic order (bubble sort) operation count = ' + count);
|
||||
|
||||
count = exponential(n);
|
||||
console.log('Exponential order (loop implementation) operation count = ' + count);
|
||||
count = expRecur(n);
|
||||
console.log('Exponential order (recursive implementation) operation count = ' + count);
|
||||
|
||||
count = logarithmic(n);
|
||||
console.log('Logarithmic order (loop implementation) operation count = ' + count);
|
||||
count = logRecur(n);
|
||||
console.log('Logarithmic order (recursive implementation) operation count = ' + count);
|
||||
|
||||
count = linearLogRecur(n);
|
||||
console.log('Linearithmic order (recursive implementation) operation count = ' + count);
|
||||
|
||||
count = factorialRecur(n);
|
||||
console.log('Factorial order (recursive implementation) operation count = ' + count);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* File: worst_best_time_complexity.ts
|
||||
* Created Time: 2023-01-05
|
||||
* Author: RiverTwilight (contact@rene.wang)
|
||||
*/
|
||||
|
||||
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
|
||||
function randomNumbers(n: number): number[] {
|
||||
const nums = Array(n);
|
||||
// Generate array nums = { 1, 2, 3, ..., n }
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = i + 1;
|
||||
}
|
||||
// Randomly shuffle array elements
|
||||
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;
|
||||
}
|
||||
|
||||
/* Find the index of number 1 in array nums */
|
||||
function findOne(nums: number[]): number {
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// When element 1 is at the head of the array, best time complexity O(1) is achieved
|
||||
// When element 1 is at the tail of the array, worst time complexity O(n) is achieved
|
||||
if (nums[i] === 1) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const n = 100;
|
||||
const nums = randomNumbers(n);
|
||||
const index = findOne(nums);
|
||||
console.log('\nArray [ 1, 2, ..., n ] after shuffling = [' + nums.join(', ') + ']');
|
||||
console.log('Index of number 1 is ' + index);
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: binary_search_recur.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary search: problem f(i, j) */
|
||||
function dfs(nums: number[], target: number, i: number, j: number): number {
|
||||
// If the interval is empty, it means there is no target element, return -1
|
||||
if (i > j) {
|
||||
return -1;
|
||||
}
|
||||
// Calculate the midpoint index m
|
||||
const m = i + ((j - i) >> 1);
|
||||
if (nums[m] < target) {
|
||||
// Recursion subproblem f(m+1, j)
|
||||
return dfs(nums, target, m + 1, j);
|
||||
} else if (nums[m] > target) {
|
||||
// Recursion subproblem f(i, m-1)
|
||||
return dfs(nums, target, i, m - 1);
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
|
||||
/* Binary search */
|
||||
function binarySearch(nums: number[], target: number): number {
|
||||
const n = nums.length;
|
||||
// Solve the problem f(0, n-1)
|
||||
return dfs(nums, target, 0, n - 1);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const target = 6;
|
||||
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
// Binary search (closed interval on both sides)
|
||||
const index = binarySearch(nums, target);
|
||||
console.log(`Index of target element 6 is ${index}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: build_tree.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
import { TreeNode } from '../modules/TreeNode';
|
||||
|
||||
/* Build binary tree: divide and conquer */
|
||||
function dfs(
|
||||
preorder: number[],
|
||||
inorderMap: Map<number, number>,
|
||||
i: number,
|
||||
l: number,
|
||||
r: number
|
||||
): TreeNode | null {
|
||||
// Terminate when the subtree interval is empty
|
||||
if (r - l < 0) return null;
|
||||
// Initialize the root node
|
||||
const root: TreeNode = new TreeNode(preorder[i]);
|
||||
// Query m to divide the left and right subtrees
|
||||
const m = inorderMap.get(preorder[i]);
|
||||
// Subproblem: build the left subtree
|
||||
root.left = dfs(preorder, inorderMap, i + 1, l, m - 1);
|
||||
// Subproblem: build the right subtree
|
||||
root.right = dfs(preorder, inorderMap, i + 1 + m - l, m + 1, r);
|
||||
// Return the root node
|
||||
return root;
|
||||
}
|
||||
|
||||
/* Build binary tree */
|
||||
function buildTree(preorder: number[], inorder: number[]): TreeNode | null {
|
||||
// Initialize hash map, storing the mapping from inorder elements to indices
|
||||
let inorderMap = new Map<number, number>();
|
||||
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;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const preorder = [3, 9, 2, 1, 7];
|
||||
const inorder = [9, 3, 1, 2, 7];
|
||||
console.log('Preorder traversal = ' + JSON.stringify(preorder));
|
||||
console.log('Inorder traversal = ' + JSON.stringify(inorder));
|
||||
const root = buildTree(preorder, inorder);
|
||||
console.log('The constructed binary tree is:');
|
||||
printTree(root);
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: hanota.ts
|
||||
* Created Time: 2023-07-30
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Move a disk */
|
||||
function move(src: number[], tar: number[]): void {
|
||||
// Take out a disk from the top of src
|
||||
const pan = src.pop();
|
||||
// Place the disk on top of tar
|
||||
tar.push(pan);
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem f(i) */
|
||||
function dfs(i: number, src: number[], buf: number[], tar: number[]): void {
|
||||
// If there is only one disk left in src, move it directly to tar
|
||||
if (i === 1) {
|
||||
move(src, tar);
|
||||
return;
|
||||
}
|
||||
// Subproblem f(i-1): move the top i-1 disks from src to buf using tar
|
||||
dfs(i - 1, src, tar, buf);
|
||||
// Subproblem f(1): move the remaining disk from src to tar
|
||||
move(src, tar);
|
||||
// Subproblem f(i-1): move the top i-1 disks from buf to tar using src
|
||||
dfs(i - 1, buf, src, tar);
|
||||
}
|
||||
|
||||
/* Solve the Tower of Hanoi problem */
|
||||
function solveHanota(A: number[], B: number[], C: number[]): void {
|
||||
const n = A.length;
|
||||
// Move the top n disks from A to C using B
|
||||
dfs(n, A, B, C);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// The tail of the list is the top of the rod
|
||||
const A = [5, 4, 3, 2, 1];
|
||||
const B = [];
|
||||
const C = [];
|
||||
console.log('In initial state:');
|
||||
console.log(`A = ${JSON.stringify(A)}`);
|
||||
console.log(`B = ${JSON.stringify(B)}`);
|
||||
console.log(`C = ${JSON.stringify(C)}`);
|
||||
|
||||
solveHanota(A, B, C);
|
||||
|
||||
console.log('After disk movement is complete:');
|
||||
console.log(`A = ${JSON.stringify(A)}`);
|
||||
console.log(`B = ${JSON.stringify(B)}`);
|
||||
console.log(`C = ${JSON.stringify(C)}`);
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: climbing_stairs_backtrack.ts
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Backtracking */
|
||||
function backtrack(
|
||||
choices: number[],
|
||||
state: number,
|
||||
n: number,
|
||||
res: Map<0, any>
|
||||
): void {
|
||||
// When climbing to the n-th stair, add 1 to the solution count
|
||||
if (state === n) res.set(0, res.get(0) + 1);
|
||||
// Traverse all choices
|
||||
for (const choice of choices) {
|
||||
// Pruning: not allowed to go beyond the n-th stair
|
||||
if (state + choice > n) continue;
|
||||
// Attempt: make choice, update state
|
||||
backtrack(choices, state + choice, n, res);
|
||||
// Backtrack
|
||||
}
|
||||
}
|
||||
|
||||
/* Climbing stairs: Backtracking */
|
||||
function climbingStairsBacktrack(n: number): number {
|
||||
const choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
|
||||
const state = 0; // Start climbing from the 0-th stair
|
||||
const res = new Map();
|
||||
res.set(0, 0); // Use res[0] to record the solution count
|
||||
backtrack(choices, state, n, res);
|
||||
return res.get(0);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsBacktrack(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_constraint_dp.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs with constraint: Dynamic programming */
|
||||
function climbingStairsConstraintDP(n: number): number {
|
||||
if (n === 1 || n === 2) {
|
||||
return 1;
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
const dp = Array.from({ length: n + 1 }, () => new Array(3));
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1][1] = 1;
|
||||
dp[1][2] = 0;
|
||||
dp[2][1] = 0;
|
||||
dp[2][2] = 1;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
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];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsConstraintDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,26 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs.ts
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Search */
|
||||
function dfs(i: number): number {
|
||||
// Known dp[1] and dp[2], return them
|
||||
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;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Search */
|
||||
function climbingStairsDFS(n: number): number {
|
||||
return dfs(n);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFS(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* File: climbing_stairs_dfs_mem.ts
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Memoization search */
|
||||
function dfs(i: number, mem: number[]): number {
|
||||
// Known dp[1] and dp[2], return them
|
||||
if (i === 1 || i === 2) return i;
|
||||
// If record dp[i] exists, return it directly
|
||||
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);
|
||||
// Record dp[i]
|
||||
mem[i] = count;
|
||||
return count;
|
||||
}
|
||||
|
||||
/* Climbing stairs: Memoization search */
|
||||
function climbingStairsDFSMem(n: number): number {
|
||||
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
|
||||
const mem = new Array(n + 1).fill(-1);
|
||||
return dfs(n, mem);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
const res = climbingStairsDFSMem(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* File: climbing_stairs_dp.ts
|
||||
* Created Time: 2023-07-26
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Climbing stairs: Dynamic programming */
|
||||
function climbingStairsDP(n: number): number {
|
||||
if (n === 1 || n === 2) return n;
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
const dp = new Array(n + 1).fill(-1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = 1;
|
||||
dp[2] = 2;
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i] = dp[i - 1] + dp[i - 2];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Climbing stairs: Space-optimized dynamic programming */
|
||||
function climbingStairsDPComp(n: number): number {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const n = 9;
|
||||
let res = climbingStairsDP(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
res = climbingStairsDPComp(n);
|
||||
console.log(`Climbing ${n} stairs has ${res} solutions`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* File: coin_change.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Dynamic programming */
|
||||
function coinChangeDP(coins: Array<number>, amt: number): number {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// State transition: first row and first column
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
dp[0][a] = MAX;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin 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;
|
||||
}
|
||||
|
||||
/* Coin change: Space-optimized dynamic programming */
|
||||
function coinChangeDPComp(coins: Array<number>, amt: number): number {
|
||||
const n = coins.length;
|
||||
const MAX = amt + 1;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => MAX);
|
||||
dp[0] = 0;
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// The smaller value between not selecting and selecting coin i
|
||||
dp[a] = Math.min(dp[a], dp[a - coins[i - 1]] + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt] !== MAX ? dp[amt] : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeDP(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeDPComp(coins, amt);
|
||||
console.log(`Minimum coins needed to make target amount is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* File: coin_change_ii.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Coin change II: Dynamic programming */
|
||||
function coinChangeIIDP(coins: Array<number>, amt: number): number {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: amt + 1 }, () => 0)
|
||||
);
|
||||
// Initialize first column
|
||||
for (let i = 0; i <= n; i++) {
|
||||
dp[i][0] = 1;
|
||||
}
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[i][a] = dp[i - 1][a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[i][a] = dp[i - 1][a] + dp[i][a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][amt];
|
||||
}
|
||||
|
||||
/* Coin change II: Space-optimized dynamic programming */
|
||||
function coinChangeIIDPComp(coins: Array<number>, amt: number): number {
|
||||
const n = coins.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: amt + 1 }, () => 0);
|
||||
dp[0] = 1;
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let a = 1; a <= amt; a++) {
|
||||
if (coins[i - 1] > a) {
|
||||
// If exceeds target amount, don't select coin i
|
||||
dp[a] = dp[a];
|
||||
} else {
|
||||
// Sum of the two options: not selecting and selecting coin i
|
||||
dp[a] = dp[a] + dp[a - coins[i - 1]];
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[amt];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const coins = [1, 2, 5];
|
||||
const amt = 5;
|
||||
|
||||
// Dynamic programming
|
||||
let res = coinChangeIIDP(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = coinChangeIIDPComp(coins, amt);
|
||||
console.log(`Number of coin combinations to make target amount is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,148 @@
|
||||
/**
|
||||
* File: edit_distance.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Edit distance: Brute-force search */
|
||||
function editDistanceDFS(s: string, t: string, i: number, j: number): number {
|
||||
// If both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFS(s, t, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 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 minimum edit steps
|
||||
return Math.min(insert, del, replace) + 1;
|
||||
}
|
||||
|
||||
/* Edit distance: Memoization search */
|
||||
function editDistanceDFSMem(
|
||||
s: string,
|
||||
t: string,
|
||||
mem: Array<Array<number>>,
|
||||
i: number,
|
||||
j: number
|
||||
): number {
|
||||
// If both s and t are empty, return 0
|
||||
if (i === 0 && j === 0) return 0;
|
||||
|
||||
// If s is empty, return length of t
|
||||
if (i === 0) return j;
|
||||
|
||||
// If t is empty, return length of s
|
||||
if (j === 0) return i;
|
||||
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] !== -1) return mem[i][j];
|
||||
|
||||
// If two characters are equal, skip both characters
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1))
|
||||
return editDistanceDFSMem(s, t, mem, i - 1, j - 1);
|
||||
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 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);
|
||||
// Record and return minimum edit steps
|
||||
mem[i][j] = Math.min(insert, del, replace) + 1;
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Edit distance: Dynamic programming */
|
||||
function editDistanceDP(s: string, t: string): number {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: m + 1 }, () => 0)
|
||||
);
|
||||
// State transition: first row and first column
|
||||
for (let i = 1; i <= n; i++) {
|
||||
dp[i][0] = i;
|
||||
}
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[0][j] = j;
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let j = 1; j <= m; j++) {
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[i][j] = dp[i - 1][j - 1];
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[i][j] =
|
||||
Math.min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) + 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][m];
|
||||
}
|
||||
|
||||
/* Edit distance: Space-optimized dynamic programming */
|
||||
function editDistanceDPComp(s: string, t: string): number {
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
const dp = new Array(m + 1).fill(0);
|
||||
// State transition: first row
|
||||
for (let j = 1; j <= m; j++) {
|
||||
dp[j] = j;
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// State transition: first column
|
||||
let leftup = dp[0]; // Temporarily store dp[i-1, j-1]
|
||||
dp[0] = i;
|
||||
// State transition: rest of the columns
|
||||
for (let j = 1; j <= m; j++) {
|
||||
const temp = dp[j];
|
||||
if (s.charAt(i - 1) === t.charAt(j - 1)) {
|
||||
// If two characters are equal, skip both characters
|
||||
dp[j] = leftup;
|
||||
} else {
|
||||
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
|
||||
dp[j] = Math.min(dp[j - 1], dp[j], leftup) + 1;
|
||||
}
|
||||
leftup = temp; // Update for next round's dp[i-1, j-1]
|
||||
}
|
||||
}
|
||||
return dp[m];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const s = 'bag';
|
||||
const t = 'pack';
|
||||
const n = s.length,
|
||||
m = t.length;
|
||||
|
||||
// Brute-force search
|
||||
let res = editDistanceDFS(s, t, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
// Memoization search
|
||||
const mem = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: m + 1 }, () => -1)
|
||||
);
|
||||
res = editDistanceDFSMem(s, t, mem, n, m);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
// Dynamic programming
|
||||
res = editDistanceDP(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = editDistanceDPComp(s, t);
|
||||
console.log(`Changing ${s} to ${t} requires minimum ${res} edits`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* File: knapsack.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* 0-1 knapsack: Brute-force search */
|
||||
function knapsackDFS(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
i: number,
|
||||
c: number
|
||||
): number {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFS(wgt, val, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item i
|
||||
const no = knapsackDFS(wgt, val, i - 1, c);
|
||||
const yes = knapsackDFS(wgt, val, i - 1, c - wgt[i - 1]) + val[i - 1];
|
||||
// Return the larger value of the two options
|
||||
return Math.max(no, yes);
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Memoization search */
|
||||
function knapsackDFSMem(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
mem: Array<Array<number>>,
|
||||
i: number,
|
||||
c: number
|
||||
): number {
|
||||
// If all items have been selected or knapsack has no remaining capacity, return value 0
|
||||
if (i === 0 || c === 0) {
|
||||
return 0;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][c] !== -1) {
|
||||
return mem[i][c];
|
||||
}
|
||||
// If exceeds knapsack capacity, can only choose not to put it in
|
||||
if (wgt[i - 1] > c) {
|
||||
return knapsackDFSMem(wgt, val, mem, i - 1, c);
|
||||
}
|
||||
// Calculate the maximum value of not putting in and putting in item 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];
|
||||
// Record and return the larger value of the two options
|
||||
mem[i][c] = Math.max(no, yes);
|
||||
return mem[i][c];
|
||||
}
|
||||
|
||||
/* 0-1 knapsack: Dynamic programming */
|
||||
function knapsackDP(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
cap: number
|
||||
): number {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => 0)
|
||||
);
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item 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 knapsack: Space-optimized dynamic programming */
|
||||
function knapsackDPComp(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
cap: number
|
||||
): number {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array(cap + 1).fill(0);
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
// Traverse in reverse order
|
||||
for (let c = cap; c >= 1; c--) {
|
||||
if (wgt[i - 1] <= c) {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const wgt = [10, 20, 30, 40, 50];
|
||||
const val = [50, 120, 150, 210, 240];
|
||||
const cap = 50;
|
||||
const n = wgt.length;
|
||||
|
||||
// Brute-force search
|
||||
let res = knapsackDFS(wgt, val, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
// Memoization search
|
||||
const mem = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => -1)
|
||||
);
|
||||
res = knapsackDFSMem(wgt, val, mem, n, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = knapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = knapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: min_cost_climbing_stairs_dp.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum cost climbing stairs: Dynamic programming */
|
||||
function minCostClimbingStairsDP(cost: Array<number>): number {
|
||||
const n = cost.length - 1;
|
||||
if (n === 1 || n === 2) {
|
||||
return cost[n];
|
||||
}
|
||||
// Initialize dp table, used to store solutions to subproblems
|
||||
const dp = new Array(n + 1);
|
||||
// Initial state: preset the solution to the smallest subproblem
|
||||
dp[1] = cost[1];
|
||||
dp[2] = cost[2];
|
||||
// State transition: gradually solve larger subproblems from smaller ones
|
||||
for (let i = 3; i <= n; i++) {
|
||||
dp[i] = Math.min(dp[i - 1], dp[i - 2]) + cost[i];
|
||||
}
|
||||
return dp[n];
|
||||
}
|
||||
|
||||
/* Minimum cost climbing stairs: Space-optimized dynamic programming */
|
||||
function minCostClimbingStairsDPComp(cost: Array<number>): number {
|
||||
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;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
|
||||
console.log(`Input stair cost list is: ${cost}`);
|
||||
|
||||
let res = minCostClimbingStairsDP(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
|
||||
res = minCostClimbingStairsDPComp(cost);
|
||||
console.log(`Minimum cost to climb stairs is: ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,132 @@
|
||||
/**
|
||||
* File: min_path_sum.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Minimum path sum: Brute-force search */
|
||||
function minPathSumDFS(
|
||||
grid: Array<Array<number>>,
|
||||
i: number,
|
||||
j: number
|
||||
): number {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i === 0 && j == 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
|
||||
const up = minPathSumDFS(grid, i - 1, j);
|
||||
const left = minPathSumDFS(grid, i, j - 1);
|
||||
// Return the minimum path cost from top-left to (i, j)
|
||||
return Math.min(left, up) + grid[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Memoization search */
|
||||
function minPathSumDFSMem(
|
||||
grid: Array<Array<number>>,
|
||||
mem: Array<Array<number>>,
|
||||
i: number,
|
||||
j: number
|
||||
): number {
|
||||
// If it's the top-left cell, terminate the search
|
||||
if (i === 0 && j === 0) {
|
||||
return grid[0][0];
|
||||
}
|
||||
// If row or column index is out of bounds, return +∞ cost
|
||||
if (i < 0 || j < 0) {
|
||||
return Infinity;
|
||||
}
|
||||
// If there's a record, return it directly
|
||||
if (mem[i][j] != -1) {
|
||||
return mem[i][j];
|
||||
}
|
||||
// Minimum path cost for left and upper cells
|
||||
const up = minPathSumDFSMem(grid, mem, i - 1, j);
|
||||
const left = minPathSumDFSMem(grid, mem, i, j - 1);
|
||||
// Record and return the minimum path cost from top-left to (i, j)
|
||||
mem[i][j] = Math.min(left, up) + grid[i][j];
|
||||
return mem[i][j];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Dynamic programming */
|
||||
function minPathSumDP(grid: Array<Array<number>>): number {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => 0)
|
||||
);
|
||||
dp[0][0] = grid[0][0];
|
||||
// State transition: first row
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[0][j] = dp[0][j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: first column
|
||||
for (let i = 1; i < n; i++) {
|
||||
dp[i][0] = dp[i - 1][0] + grid[i][0];
|
||||
}
|
||||
// State transition: rest of the rows and columns
|
||||
for (let i = 1; i < n; i++) {
|
||||
for (let j: number = 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];
|
||||
}
|
||||
|
||||
/* Minimum path sum: Space-optimized dynamic programming */
|
||||
function minPathSumDPComp(grid: Array<Array<number>>): number {
|
||||
const n = grid.length,
|
||||
m = grid[0].length;
|
||||
// Initialize dp table
|
||||
const dp = new Array(m);
|
||||
// State transition: first row
|
||||
dp[0] = grid[0][0];
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = dp[j - 1] + grid[0][j];
|
||||
}
|
||||
// State transition: rest of the rows
|
||||
for (let i = 1; i < n; i++) {
|
||||
// State transition: first column
|
||||
dp[0] = dp[0] + grid[i][0];
|
||||
// State transition: rest of the columns
|
||||
for (let j = 1; j < m; j++) {
|
||||
dp[j] = Math.min(dp[j - 1], dp[j]) + grid[i][j];
|
||||
}
|
||||
}
|
||||
return dp[m - 1];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
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;
|
||||
// Brute-force search
|
||||
let res = minPathSumDFS(grid, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
|
||||
// Memoization search
|
||||
const mem = Array.from({ length: n }, () =>
|
||||
Array.from({ length: m }, () => -1)
|
||||
);
|
||||
res = minPathSumDFSMem(grid, mem, n - 1, m - 1);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
|
||||
// Dynamic programming
|
||||
res = minPathSumDP(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = minPathSumDPComp(grid);
|
||||
console.log(`Minimum path sum from top-left to bottom-right is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,73 @@
|
||||
/**
|
||||
* File: unbounded_knapsack.ts
|
||||
* Created Time: 2023-08-23
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Unbounded knapsack: Dynamic programming */
|
||||
function unboundedKnapsackDP(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
cap: number
|
||||
): number {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: n + 1 }, () =>
|
||||
Array.from({ length: cap + 1 }, () => 0)
|
||||
);
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[i][c] = dp[i - 1][c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[i][c] = Math.max(
|
||||
dp[i - 1][c],
|
||||
dp[i][c - wgt[i - 1]] + val[i - 1]
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[n][cap];
|
||||
}
|
||||
|
||||
/* Unbounded knapsack: Space-optimized dynamic programming */
|
||||
function unboundedKnapsackDPComp(
|
||||
wgt: Array<number>,
|
||||
val: Array<number>,
|
||||
cap: number
|
||||
): number {
|
||||
const n = wgt.length;
|
||||
// Initialize dp table
|
||||
const dp = Array.from({ length: cap + 1 }, () => 0);
|
||||
// State transition
|
||||
for (let i = 1; i <= n; i++) {
|
||||
for (let c = 1; c <= cap; c++) {
|
||||
if (wgt[i - 1] > c) {
|
||||
// If exceeds knapsack capacity, don't select item i
|
||||
dp[c] = dp[c];
|
||||
} else {
|
||||
// The larger value between not selecting and selecting item i
|
||||
dp[c] = Math.max(dp[c], dp[c - wgt[i - 1]] + val[i - 1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return dp[cap];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const wgt = [1, 2, 3];
|
||||
const val = [5, 11, 15];
|
||||
const cap = 4;
|
||||
|
||||
// Dynamic programming
|
||||
let res = unboundedKnapsackDP(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
// Space-optimized dynamic programming
|
||||
res = unboundedKnapsackDPComp(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* File: graph_adjacency_list.ts
|
||||
* Created Time: 2023-02-09
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { Vertex } from '../modules/Vertex';
|
||||
|
||||
/* Undirected graph class based on adjacency list */
|
||||
class GraphAdjList {
|
||||
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
|
||||
adjList: Map<Vertex, Vertex[]>;
|
||||
|
||||
/* Constructor */
|
||||
constructor(edges: Vertex[][]) {
|
||||
this.adjList = new Map();
|
||||
// Add all vertices and edges
|
||||
for (const edge of edges) {
|
||||
this.addVertex(edge[0]);
|
||||
this.addVertex(edge[1]);
|
||||
this.addEdge(edge[0], edge[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
size(): number {
|
||||
return this.adjList.size;
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
addEdge(vet1: Vertex, vet2: Vertex): void {
|
||||
if (
|
||||
!this.adjList.has(vet1) ||
|
||||
!this.adjList.has(vet2) ||
|
||||
vet1 === vet2
|
||||
) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
}
|
||||
// Add edge vet1 - vet2
|
||||
this.adjList.get(vet1).push(vet2);
|
||||
this.adjList.get(vet2).push(vet1);
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
removeEdge(vet1: Vertex, vet2: Vertex): void {
|
||||
if (
|
||||
!this.adjList.has(vet1) ||
|
||||
!this.adjList.has(vet2) ||
|
||||
vet1 === vet2 ||
|
||||
this.adjList.get(vet1).indexOf(vet2) === -1
|
||||
) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
}
|
||||
// Remove edge 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);
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
addVertex(vet: Vertex): void {
|
||||
if (this.adjList.has(vet)) return;
|
||||
// Add a new linked list in the adjacency list
|
||||
this.adjList.set(vet, []);
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
removeVertex(vet: Vertex): void {
|
||||
if (!this.adjList.has(vet)) {
|
||||
throw new Error('Illegal Argument Exception');
|
||||
}
|
||||
// Remove the linked list corresponding to vertex vet in the adjacency list
|
||||
this.adjList.delete(vet);
|
||||
// Traverse the linked lists of other vertices and remove all edges containing vet
|
||||
for (const set of this.adjList.values()) {
|
||||
const index: number = set.indexOf(vet);
|
||||
if (index > -1) {
|
||||
set.splice(index, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print adjacency list */
|
||||
print(): void {
|
||||
console.log('Adjacency list =');
|
||||
for (const [key, value] of this.adjList.entries()) {
|
||||
const tmp = [];
|
||||
for (const vertex of value) {
|
||||
tmp.push(vertex.val);
|
||||
}
|
||||
console.log(key.val + ': ' + tmp.join());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
if (import.meta.url.endsWith(process.argv[1])) {
|
||||
/* Add edge */
|
||||
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('\nAfter initialization, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Vertices 1, 2 are v0, v2
|
||||
graph.addEdge(v0, v2);
|
||||
console.log('\nAfter adding edge 1-2, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 are v0, v1
|
||||
graph.removeEdge(v0, v1);
|
||||
console.log('\nAfter removing edge 1-3, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
const v5 = new Vertex(6);
|
||||
graph.addVertex(v5);
|
||||
console.log('\nAfter adding vertex 6, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 is v1
|
||||
graph.removeVertex(v1);
|
||||
console.log('\nAfter removing vertex 3, graph is');
|
||||
graph.print();
|
||||
}
|
||||
|
||||
export { GraphAdjList };
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* File: graph_adjacency_matrix.ts
|
||||
* Created Time: 2023-02-09
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Undirected graph class based on adjacency matrix */
|
||||
class GraphAdjMat {
|
||||
vertices: number[]; // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
|
||||
adjMat: number[][]; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
|
||||
|
||||
/* Constructor */
|
||||
constructor(vertices: number[], edges: number[][]) {
|
||||
this.vertices = [];
|
||||
this.adjMat = [];
|
||||
// Add vertex
|
||||
for (const val of vertices) {
|
||||
this.addVertex(val);
|
||||
}
|
||||
// Add edge
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
for (const e of edges) {
|
||||
this.addEdge(e[0], e[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get the number of vertices */
|
||||
size(): number {
|
||||
return this.vertices.length;
|
||||
}
|
||||
|
||||
/* Add vertex */
|
||||
addVertex(val: number): void {
|
||||
const n: number = this.size();
|
||||
// Add the value of the new vertex to the vertex list
|
||||
this.vertices.push(val);
|
||||
// Add a row to the adjacency matrix
|
||||
const newRow: number[] = [];
|
||||
for (let j: number = 0; j < n; j++) {
|
||||
newRow.push(0);
|
||||
}
|
||||
this.adjMat.push(newRow);
|
||||
// Add a column to the adjacency matrix
|
||||
for (const row of this.adjMat) {
|
||||
row.push(0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Remove vertex */
|
||||
removeVertex(index: number): void {
|
||||
if (index >= this.size()) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
}
|
||||
// Remove the vertex at index from the vertex list
|
||||
this.vertices.splice(index, 1);
|
||||
|
||||
// Remove the row at index from the adjacency matrix
|
||||
this.adjMat.splice(index, 1);
|
||||
// Remove the column at index from the adjacency matrix
|
||||
for (const row of this.adjMat) {
|
||||
row.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/* Add edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
addEdge(i: number, j: number): void {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
}
|
||||
// In undirected graph, adjacency matrix is symmetric about main diagonal, i.e., satisfies (i, j) === (j, i)
|
||||
this.adjMat[i][j] = 1;
|
||||
this.adjMat[j][i] = 1;
|
||||
}
|
||||
|
||||
/* Remove edge */
|
||||
// Parameters i, j correspond to the vertices element indices
|
||||
removeEdge(i: number, j: number): void {
|
||||
// Handle index out of bounds and equality
|
||||
if (i < 0 || j < 0 || i >= this.size() || j >= this.size() || i === j) {
|
||||
throw new RangeError('Index Out Of Bounds Exception');
|
||||
}
|
||||
this.adjMat[i][j] = 0;
|
||||
this.adjMat[j][i] = 0;
|
||||
}
|
||||
|
||||
/* Print adjacency matrix */
|
||||
print(): void {
|
||||
console.log('Vertex list = ', this.vertices);
|
||||
console.log('Adjacency matrix =', this.adjMat);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
|
||||
const vertices: number[] = [1, 3, 2, 5, 4];
|
||||
const edges: number[][] = [
|
||||
[0, 1],
|
||||
[1, 2],
|
||||
[2, 3],
|
||||
[0, 3],
|
||||
[2, 4],
|
||||
[3, 4],
|
||||
];
|
||||
const graph: GraphAdjMat = new GraphAdjMat(vertices, edges);
|
||||
console.log('\nAfter initialization, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Add edge */
|
||||
// Add vertex
|
||||
graph.addEdge(0, 2);
|
||||
console.log('\nAfter adding edge 1-2, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Remove edge */
|
||||
// Vertices 1, 3 have indices 0, 1 respectively
|
||||
graph.removeEdge(0, 1);
|
||||
console.log('\nAfter removing edge 1-3, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Add vertex */
|
||||
graph.addVertex(6);
|
||||
console.log('\nAfter adding vertex 6, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Remove vertex */
|
||||
// Vertex 3 has index 1
|
||||
graph.removeVertex(1);
|
||||
console.log('\nAfter removing vertex 3, graph is');
|
||||
graph.print();
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* File: graph_bfs.ts
|
||||
* Created Time: 2023-02-21
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
import { GraphAdjList } from './graph_adjacency_list';
|
||||
import { Vertex } from '../modules/Vertex';
|
||||
|
||||
/* Breadth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
function graphBFS(graph: GraphAdjList, startVet: Vertex): Vertex[] {
|
||||
// Vertex traversal sequence
|
||||
const res: Vertex[] = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
const visited: Set<Vertex> = new Set();
|
||||
visited.add(startVet);
|
||||
// Queue used to implement BFS
|
||||
const que = [startVet];
|
||||
// Starting from vertex vet, loop until all vertices are visited
|
||||
while (que.length) {
|
||||
const vet = que.shift(); // Dequeue the front vertex
|
||||
res.push(vet); // Record visited vertex
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for (const adjVet of graph.adjList.get(vet) ?? []) {
|
||||
if (visited.has(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
}
|
||||
que.push(adjVet); // Only enqueue unvisited
|
||||
visited.add(adjVet); // Mark this vertex as visited
|
||||
}
|
||||
}
|
||||
// Return vertex traversal sequence
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
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('\nAfter initialization, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Breadth-first traversal */
|
||||
const res = graphBFS(graph, v[0]);
|
||||
console.log('\nBreadth-first traversal (BFS) vertex sequence is');
|
||||
console.log(Vertex.vetsToVals(res));
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* File: graph_dfs.ts
|
||||
* Created Time: 2023-02-21
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
import { Vertex } from '../modules/Vertex';
|
||||
import { GraphAdjList } from './graph_adjacency_list';
|
||||
|
||||
/* Depth-first traversal helper function */
|
||||
function dfs(
|
||||
graph: GraphAdjList,
|
||||
visited: Set<Vertex>,
|
||||
res: Vertex[],
|
||||
vet: Vertex
|
||||
): void {
|
||||
res.push(vet); // Record visited vertex
|
||||
visited.add(vet); // Mark this vertex as visited
|
||||
// Traverse all adjacent vertices of this vertex
|
||||
for (const adjVet of graph.adjList.get(vet)) {
|
||||
if (visited.has(adjVet)) {
|
||||
continue; // Skip vertices that have been visited
|
||||
}
|
||||
// Recursively visit adjacent vertices
|
||||
dfs(graph, visited, res, adjVet);
|
||||
}
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
|
||||
function graphDFS(graph: GraphAdjList, startVet: Vertex): Vertex[] {
|
||||
// Vertex traversal sequence
|
||||
const res: Vertex[] = [];
|
||||
// Hash set for recording vertices that have been visited
|
||||
const visited: Set<Vertex> = new Set();
|
||||
dfs(graph, visited, res, startVet);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Add edge */
|
||||
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('\nAfter initialization, graph is');
|
||||
graph.print();
|
||||
|
||||
/* Depth-first traversal */
|
||||
const res = graphDFS(graph, v[0]);
|
||||
console.log('\nDepth-first traversal (DFS) vertex sequence is');
|
||||
console.log(Vertex.vetsToVals(res));
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: coin_change_greedy.ts
|
||||
* Created Time: 2023-09-02
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Coin change: Greedy algorithm */
|
||||
function coinChangeGreedy(coins: number[], amt: number): number {
|
||||
// Assume coins array is sorted
|
||||
let i = coins.length - 1;
|
||||
let count = 0;
|
||||
// Loop to make greedy choices until no remaining amount
|
||||
while (amt > 0) {
|
||||
// Find the coin that is less than and closest to the remaining amount
|
||||
while (i > 0 && coins[i] > amt) {
|
||||
i--;
|
||||
}
|
||||
// Choose coins[i]
|
||||
amt -= coins[i];
|
||||
count++;
|
||||
}
|
||||
// If no feasible solution is found, return -1
|
||||
return amt === 0 ? count : -1;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Greedy algorithm: Can guarantee finding the global optimal solution
|
||||
let coins: number[] = [1, 5, 10, 20, 50, 100];
|
||||
let amt: number = 186;
|
||||
let res: number = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 20, 50];
|
||||
amt = 60;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
console.log('Actually the minimum number needed is 3, i.e., 20 + 20 + 20');
|
||||
|
||||
// Greedy algorithm: Cannot guarantee finding the global optimal solution
|
||||
coins = [1, 49, 50];
|
||||
amt = 98;
|
||||
res = coinChangeGreedy(coins, amt);
|
||||
console.log(`\ncoins = ${coins}, amt = ${amt}`);
|
||||
console.log(`Minimum coins needed to make ${amt} is ${res}`);
|
||||
console.log('Actually the minimum number needed is 2, i.e., 49 + 49');
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: fractional_knapsack.ts
|
||||
* Created Time: 2023-09-02
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Item */
|
||||
class Item {
|
||||
w: number; // Item weight
|
||||
v: number; // Item value
|
||||
|
||||
constructor(w: number, v: number) {
|
||||
this.w = w;
|
||||
this.v = v;
|
||||
}
|
||||
}
|
||||
|
||||
/* Fractional knapsack: Greedy algorithm */
|
||||
function fractionalKnapsack(wgt: number[], val: number[], cap: number): number {
|
||||
// Create item list with two attributes: weight, value
|
||||
const items: Item[] = wgt.map((w, i) => new Item(w, val[i]));
|
||||
// Sort by unit value item.v / item.w from high to low
|
||||
items.sort((a, b) => b.v / b.w - a.v / a.w);
|
||||
// Loop for greedy selection
|
||||
let res = 0;
|
||||
for (const item of items) {
|
||||
if (item.w <= cap) {
|
||||
// If remaining capacity is sufficient, put the entire current item into the knapsack
|
||||
res += item.v;
|
||||
cap -= item.w;
|
||||
} else {
|
||||
// If remaining capacity is insufficient, put part of the current item into the knapsack
|
||||
res += (item.v / item.w) * cap;
|
||||
// No remaining capacity, so break out of the loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const wgt: number[] = [10, 20, 30, 40, 50];
|
||||
const val: number[] = [50, 120, 150, 210, 240];
|
||||
const cap: number = 50;
|
||||
|
||||
// Greedy algorithm
|
||||
const res: number = fractionalKnapsack(wgt, val, cap);
|
||||
console.log(`Maximum item value not exceeding knapsack capacity is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,36 @@
|
||||
/**
|
||||
* File: max_capacity.ts
|
||||
* Created Time: 2023-09-02
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Max capacity: Greedy algorithm */
|
||||
function maxCapacity(ht: number[]): number {
|
||||
// Initialize i, j to be at both ends of the array
|
||||
let i = 0,
|
||||
j = ht.length - 1;
|
||||
// Initial max capacity is 0
|
||||
let res = 0;
|
||||
// Loop for greedy selection until the two boards meet
|
||||
while (i < j) {
|
||||
// Update max capacity
|
||||
const cap: number = Math.min(ht[i], ht[j]) * (j - i);
|
||||
res = Math.max(res, cap);
|
||||
// Move the shorter board inward
|
||||
if (ht[i] < ht[j]) {
|
||||
i += 1;
|
||||
} else {
|
||||
j -= 1;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const ht: number[] = [3, 8, 5, 2, 7, 7, 3, 4];
|
||||
|
||||
// Greedy algorithm
|
||||
const res: number = maxCapacity(ht);
|
||||
console.log(`Maximum capacity is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* File: max_product_cutting.ts
|
||||
* Created Time: 2023-09-02
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Max product cutting: Greedy algorithm */
|
||||
function maxProductCutting(n: number): number {
|
||||
// When n <= 3, must cut out a 1
|
||||
if (n <= 3) {
|
||||
return 1 * (n - 1);
|
||||
}
|
||||
// Greedily cut out 3, a is the number of 3s, b is the remainder
|
||||
let a: number = Math.floor(n / 3);
|
||||
let b: number = n % 3;
|
||||
if (b === 1) {
|
||||
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
|
||||
return Math.pow(3, a - 1) * 2 * 2;
|
||||
}
|
||||
if (b === 2) {
|
||||
// When the remainder is 2, do nothing
|
||||
return Math.pow(3, a) * 2;
|
||||
}
|
||||
// When the remainder is 0, do nothing
|
||||
return Math.pow(3, a);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
let n: number = 58;
|
||||
|
||||
// Greedy algorithm
|
||||
let res: number = maxProductCutting(n);
|
||||
console.log(`Maximum cutting product is ${res}`);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* File: array_hash_map.ts
|
||||
* Created Time: 2022-12-20
|
||||
* Author: Daniel (better.sunjian@gmail.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
class Pair {
|
||||
public key: number;
|
||||
public val: string;
|
||||
|
||||
constructor(key: number, val: string) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash table based on array implementation */
|
||||
class ArrayHashMap {
|
||||
private readonly buckets: (Pair | null)[];
|
||||
|
||||
constructor() {
|
||||
// Initialize array with 100 buckets
|
||||
this.buckets = new Array(100).fill(null);
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
private hashFunc(key: number): number {
|
||||
return key % 100;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
public get(key: number): string | null {
|
||||
let index = this.hashFunc(key);
|
||||
let pair = this.buckets[index];
|
||||
if (pair === null) return null;
|
||||
return pair.val;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
public set(key: number, val: string) {
|
||||
let index = this.hashFunc(key);
|
||||
this.buckets[index] = new Pair(key, val);
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
public delete(key: number) {
|
||||
let index = this.hashFunc(key);
|
||||
// Set to null to represent deletion
|
||||
this.buckets[index] = null;
|
||||
}
|
||||
|
||||
/* Get all key-value pairs */
|
||||
public entries(): (Pair | null)[] {
|
||||
let arr: (Pair | null)[] = [];
|
||||
for (let i = 0; i < this.buckets.length; i++) {
|
||||
if (this.buckets[i]) {
|
||||
arr.push(this.buckets[i]);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Get all keys */
|
||||
public keys(): (number | undefined)[] {
|
||||
let arr: (number | undefined)[] = [];
|
||||
for (let i = 0; i < this.buckets.length; i++) {
|
||||
if (this.buckets[i]) {
|
||||
arr.push(this.buckets[i].key);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Get all values */
|
||||
public values(): (string | undefined)[] {
|
||||
let arr: (string | undefined)[] = [];
|
||||
for (let i = 0; i < this.buckets.length; i++) {
|
||||
if (this.buckets[i]) {
|
||||
arr.push(this.buckets[i].val);
|
||||
}
|
||||
}
|
||||
return arr;
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
public print() {
|
||||
let pairSet = this.entries();
|
||||
for (const pair of pairSet) {
|
||||
console.info(`${pair.key} -> ${pair.val}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
const map = new ArrayHashMap();
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.set(12836, 'Xiao Ha');
|
||||
map.set(15937, 'Xiao Luo');
|
||||
map.set(16750, 'Xiao Suan');
|
||||
map.set(13276, 'Xiao Fa');
|
||||
map.set(10583, 'Xiao Ya');
|
||||
console.info('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map.get(15937);
|
||||
console.info('\nInput student ID 15937, query name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.delete(10583);
|
||||
console.info('\nAfter removing 10583, hash table is\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Traverse hash table */
|
||||
console.info('\nTraverse key-value pairs Key->Value');
|
||||
for (const pair of map.entries()) {
|
||||
if (!pair) continue;
|
||||
console.info(pair.key + ' -> ' + pair.val);
|
||||
}
|
||||
console.info('\nTraverse keys only Key');
|
||||
for (const key of map.keys()) {
|
||||
console.info(key);
|
||||
}
|
||||
console.info('\nTraverse values only Value');
|
||||
for (const val of map.values()) {
|
||||
console.info(val);
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: hash_map.ts
|
||||
* Created Time: 2022-12-20
|
||||
* Author: Daniel (better.sunjian@gmail.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
const map = new Map<number, string>();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.set(12836, 'Xiao Ha');
|
||||
map.set(15937, 'Xiao Luo');
|
||||
map.set(16750, 'Xiao Suan');
|
||||
map.set(13276, 'Xiao Fa');
|
||||
map.set(10583, 'Xiao Ya');
|
||||
console.info('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
console.info(map);
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
let name = map.get(15937);
|
||||
console.info('\nInput student ID 15937, query name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.delete(10583);
|
||||
console.info('\nAfter removing 10583, hash table is\nKey -> Value');
|
||||
console.info(map);
|
||||
|
||||
/* Traverse hash table */
|
||||
console.info('\nTraverse key-value pairs Key->Value');
|
||||
for (const [k, v] of map.entries()) {
|
||||
console.info(k + ' -> ' + v);
|
||||
}
|
||||
console.info('\nTraverse keys only Key');
|
||||
for (const k of map.keys()) {
|
||||
console.info(k);
|
||||
}
|
||||
console.info('\nTraverse values only Value');
|
||||
for (const v of map.values()) {
|
||||
console.info(v);
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* File: hash_map_chaining.ts
|
||||
* Created Time: 2023-08-06
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
class Pair {
|
||||
key: number;
|
||||
val: string;
|
||||
constructor(key: number, val: string) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash table with separate chaining */
|
||||
class HashMapChaining {
|
||||
#size: number; // Number of key-value pairs
|
||||
#capacity: number; // Hash table capacity
|
||||
#loadThres: number; // Load factor threshold for triggering expansion
|
||||
#extendRatio: number; // Expansion multiplier
|
||||
#buckets: Pair[][]; // Bucket array
|
||||
|
||||
/* Constructor */
|
||||
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) => []);
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
#hashFunc(key: number): number {
|
||||
return key % this.#capacity;
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
#loadFactor(): number {
|
||||
return this.#size / this.#capacity;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
get(key: number): string | null {
|
||||
const index = this.#hashFunc(key);
|
||||
const bucket = this.#buckets[index];
|
||||
// Traverse bucket, if key is found, return corresponding val
|
||||
for (const pair of bucket) {
|
||||
if (pair.key === key) {
|
||||
return pair.val;
|
||||
}
|
||||
}
|
||||
// If key is not found, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
put(key: number, val: string): void {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if (this.#loadFactor() > this.#loadThres) {
|
||||
this.#extend();
|
||||
}
|
||||
const index = this.#hashFunc(key);
|
||||
const bucket = this.#buckets[index];
|
||||
// Traverse bucket, if specified key is encountered, update corresponding val and return
|
||||
for (const pair of bucket) {
|
||||
if (pair.key === key) {
|
||||
pair.val = val;
|
||||
return;
|
||||
}
|
||||
}
|
||||
// If key does not exist, append key-value pair to the end
|
||||
const pair = new Pair(key, val);
|
||||
bucket.push(pair);
|
||||
this.#size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
remove(key: number): void {
|
||||
const index = this.#hashFunc(key);
|
||||
let bucket = this.#buckets[index];
|
||||
// Traverse bucket and remove key-value pair from it
|
||||
for (let i = 0; i < bucket.length; i++) {
|
||||
if (bucket[i].key === key) {
|
||||
bucket.splice(i, 1);
|
||||
this.#size--;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
#extend(): void {
|
||||
// Temporarily store the original hash table
|
||||
const bucketsTmp = this.#buckets;
|
||||
// Initialize expanded new hash table
|
||||
this.#capacity *= this.#extendRatio;
|
||||
this.#buckets = new Array(this.#capacity).fill(null).map((x) => []);
|
||||
this.#size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for (const bucket of bucketsTmp) {
|
||||
for (const pair of bucket) {
|
||||
this.put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
print(): void {
|
||||
for (const bucket of this.#buckets) {
|
||||
let res = [];
|
||||
for (const pair of bucket) {
|
||||
res.push(pair.key + ' -> ' + pair.val);
|
||||
}
|
||||
console.log(res);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize hash table */
|
||||
const map = new HashMapChaining();
|
||||
|
||||
/* Add operation */
|
||||
// Add key-value pair (key, value) to the hash table
|
||||
map.put(12836, 'Xiao Ha');
|
||||
map.put(15937, 'Xiao Luo');
|
||||
map.put(16750, 'Xiao Suan');
|
||||
map.put(13276, 'Xiao Fa');
|
||||
map.put(10583, 'Xiao Ya');
|
||||
console.log('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
/* Query operation */
|
||||
// Input key into hash table to get value
|
||||
const name = map.get(13276);
|
||||
console.log('\nInput student ID 13276, query name ' + name);
|
||||
|
||||
/* Remove operation */
|
||||
// Remove key-value pair (key, value) from hash table
|
||||
map.remove(12836);
|
||||
console.log('\nAfter removing 12836, hash table is\nKey -> Value');
|
||||
map.print();
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,182 @@
|
||||
/**
|
||||
* File: hash_map_open_addressing.ts
|
||||
* Created Time: 2023-08-06
|
||||
* Author: yuan0221 (yl1452491917@gmail.com), krahets (krahets@163.com)
|
||||
*/
|
||||
|
||||
/* Key-value pair Number -> String */
|
||||
class Pair {
|
||||
key: number;
|
||||
val: string;
|
||||
|
||||
constructor(key: number, val: string) {
|
||||
this.key = key;
|
||||
this.val = val;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hash table with open addressing */
|
||||
class HashMapOpenAddressing {
|
||||
private size: number; // Number of key-value pairs
|
||||
private capacity: number; // Hash table capacity
|
||||
private loadThres: number; // Load factor threshold for triggering expansion
|
||||
private extendRatio: number; // Expansion multiplier
|
||||
private buckets: Array<Pair | null>; // Bucket array
|
||||
private TOMBSTONE: Pair; // Removal marker
|
||||
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.size = 0; // Number of key-value pairs
|
||||
this.capacity = 4; // Hash table capacity
|
||||
this.loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
|
||||
this.extendRatio = 2; // Expansion multiplier
|
||||
this.buckets = Array(this.capacity).fill(null); // Bucket array
|
||||
this.TOMBSTONE = new Pair(-1, '-1'); // Removal marker
|
||||
}
|
||||
|
||||
/* Hash function */
|
||||
private hashFunc(key: number): number {
|
||||
return key % this.capacity;
|
||||
}
|
||||
|
||||
/* Load factor */
|
||||
private loadFactor(): number {
|
||||
return this.size / this.capacity;
|
||||
}
|
||||
|
||||
/* Search for bucket index corresponding to key */
|
||||
private findBucket(key: number): number {
|
||||
let index = this.hashFunc(key);
|
||||
let firstTombstone = -1;
|
||||
// Linear probing, break when encountering an empty bucket
|
||||
while (this.buckets[index] !== null) {
|
||||
// If key is encountered, return the corresponding bucket index
|
||||
if (this.buckets[index]!.key === key) {
|
||||
// If a removal marker was encountered before, move the key-value pair to that index
|
||||
if (firstTombstone !== -1) {
|
||||
this.buckets[firstTombstone] = this.buckets[index];
|
||||
this.buckets[index] = this.TOMBSTONE;
|
||||
return firstTombstone; // Return the moved bucket index
|
||||
}
|
||||
return index; // Return bucket index
|
||||
}
|
||||
// Record the first removal marker encountered
|
||||
if (
|
||||
firstTombstone === -1 &&
|
||||
this.buckets[index] === this.TOMBSTONE
|
||||
) {
|
||||
firstTombstone = index;
|
||||
}
|
||||
// Calculate bucket index, wrap around to the head if past the tail
|
||||
index = (index + 1) % this.capacity;
|
||||
}
|
||||
// If key does not exist, return the index for insertion
|
||||
return firstTombstone === -1 ? index : firstTombstone;
|
||||
}
|
||||
|
||||
/* Query operation */
|
||||
get(key: number): string | null {
|
||||
// Search for bucket index corresponding to key
|
||||
const index = this.findBucket(key);
|
||||
// If key-value pair is found, return corresponding val
|
||||
if (
|
||||
this.buckets[index] !== null &&
|
||||
this.buckets[index] !== this.TOMBSTONE
|
||||
) {
|
||||
return this.buckets[index]!.val;
|
||||
}
|
||||
// If key-value pair does not exist, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Add operation */
|
||||
put(key: number, val: string): void {
|
||||
// When load factor exceeds threshold, perform expansion
|
||||
if (this.loadFactor() > this.loadThres) {
|
||||
this.extend();
|
||||
}
|
||||
// Search for bucket index corresponding to key
|
||||
const index = this.findBucket(key);
|
||||
// If key-value pair is found, overwrite val and return
|
||||
if (
|
||||
this.buckets[index] !== null &&
|
||||
this.buckets[index] !== this.TOMBSTONE
|
||||
) {
|
||||
this.buckets[index]!.val = val;
|
||||
return;
|
||||
}
|
||||
// If key-value pair does not exist, add the key-value pair
|
||||
this.buckets[index] = new Pair(key, val);
|
||||
this.size++;
|
||||
}
|
||||
|
||||
/* Remove operation */
|
||||
remove(key: number): void {
|
||||
// Search for bucket index corresponding to key
|
||||
const index = this.findBucket(key);
|
||||
// If key-value pair is found, overwrite it with removal marker
|
||||
if (
|
||||
this.buckets[index] !== null &&
|
||||
this.buckets[index] !== this.TOMBSTONE
|
||||
) {
|
||||
this.buckets[index] = this.TOMBSTONE;
|
||||
this.size--;
|
||||
}
|
||||
}
|
||||
|
||||
/* Expand hash table */
|
||||
private extend(): void {
|
||||
// Temporarily store the original hash table
|
||||
const bucketsTmp = this.buckets;
|
||||
// Initialize expanded new hash table
|
||||
this.capacity *= this.extendRatio;
|
||||
this.buckets = Array(this.capacity).fill(null);
|
||||
this.size = 0;
|
||||
// Move key-value pairs from original hash table to new hash table
|
||||
for (const pair of bucketsTmp) {
|
||||
if (pair !== null && pair !== this.TOMBSTONE) {
|
||||
this.put(pair.key, pair.val);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Print hash table */
|
||||
print(): void {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Initialize hash table
|
||||
const hashmap = new HashMapOpenAddressing();
|
||||
|
||||
// Add operation
|
||||
// Add key-value pair (key, val) to the hash table
|
||||
hashmap.put(12836, 'Xiao Ha');
|
||||
hashmap.put(15937, 'Xiao Luo');
|
||||
hashmap.put(16750, 'Xiao Suan');
|
||||
hashmap.put(13276, 'Xiao Fa');
|
||||
hashmap.put(10583, 'Xiao Ya');
|
||||
console.log('\nAfter adding is complete, hash table is\nKey -> Value');
|
||||
hashmap.print();
|
||||
|
||||
// Query operation
|
||||
// Input key into hash table to get value val
|
||||
const name = hashmap.get(13276);
|
||||
console.log('\nInput student ID 13276, query name ' + name);
|
||||
|
||||
// Remove operation
|
||||
// Remove key-value pair (key, val) from hash table
|
||||
hashmap.remove(16750);
|
||||
console.log('\nAfter removing 16750, hash table is\nKey -> Value');
|
||||
hashmap.print();
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* File: simple_hash.ts
|
||||
* Created Time: 2023-08-06
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
/* Additive hash */
|
||||
function addHash(key: string): number {
|
||||
let hash = 0;
|
||||
const MODULUS = 1000000007;
|
||||
for (const c of key) {
|
||||
hash = (hash + c.charCodeAt(0)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* Multiplicative hash */
|
||||
function mulHash(key: string): number {
|
||||
let hash = 0;
|
||||
const MODULUS = 1000000007;
|
||||
for (const c of key) {
|
||||
hash = (31 * hash + c.charCodeAt(0)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* XOR hash */
|
||||
function xorHash(key: string): number {
|
||||
let hash = 0;
|
||||
const MODULUS = 1000000007;
|
||||
for (const c of key) {
|
||||
hash ^= c.charCodeAt(0);
|
||||
}
|
||||
return hash % MODULUS;
|
||||
}
|
||||
|
||||
/* Rotational hash */
|
||||
function rotHash(key: string): number {
|
||||
let hash = 0;
|
||||
const MODULUS = 1000000007;
|
||||
for (const c of key) {
|
||||
hash = ((hash << 4) ^ (hash >> 28) ^ c.charCodeAt(0)) % MODULUS;
|
||||
}
|
||||
return hash;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const key = 'Hello Algo';
|
||||
|
||||
let hash = addHash(key);
|
||||
console.log('Additive hash value is ' + hash);
|
||||
|
||||
hash = mulHash(key);
|
||||
console.log('Multiplicative hash value is ' + hash);
|
||||
|
||||
hash = xorHash(key);
|
||||
console.log('XOR hash value is ' + hash);
|
||||
|
||||
hash = rotHash(key);
|
||||
console.log('Rotational hash value is ' + hash);
|
||||
@@ -0,0 +1,155 @@
|
||||
/**
|
||||
* File: my_heap.ts
|
||||
* Created Time: 2023-02-07
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { printHeap } from '../modules/PrintUtil';
|
||||
|
||||
/* Max heap class */
|
||||
class MaxHeap {
|
||||
private maxHeap: number[];
|
||||
/* Constructor, build empty heap or build heap from input list */
|
||||
constructor(nums?: number[]) {
|
||||
// Add list elements to heap as is
|
||||
this.maxHeap = nums === undefined ? [] : [...nums];
|
||||
// Heapify all nodes except leaf nodes
|
||||
for (let i = this.parent(this.size() - 1); i >= 0; i--) {
|
||||
this.siftDown(i);
|
||||
}
|
||||
}
|
||||
|
||||
/* Get index of left child node */
|
||||
private left(i: number): number {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node */
|
||||
private right(i: number): number {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node */
|
||||
private parent(i: number): number {
|
||||
return Math.floor((i - 1) / 2); // Floor division
|
||||
}
|
||||
|
||||
/* Swap elements */
|
||||
private swap(i: number, j: number): void {
|
||||
const tmp = this.maxHeap[i];
|
||||
this.maxHeap[i] = this.maxHeap[j];
|
||||
this.maxHeap[j] = tmp;
|
||||
}
|
||||
|
||||
/* Get heap size */
|
||||
public size(): number {
|
||||
return this.maxHeap.length;
|
||||
}
|
||||
|
||||
/* Check if heap is empty */
|
||||
public isEmpty(): boolean {
|
||||
return this.size() === 0;
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
public peek(): number {
|
||||
return this.maxHeap[0];
|
||||
}
|
||||
|
||||
/* Element enters heap */
|
||||
public push(val: number): void {
|
||||
// Add node
|
||||
this.maxHeap.push(val);
|
||||
// Heapify from bottom to top
|
||||
this.siftUp(this.size() - 1);
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from bottom to top */
|
||||
private siftUp(i: number): void {
|
||||
while (true) {
|
||||
// Get parent node of node i
|
||||
const p = this.parent(i);
|
||||
// When "crossing root node" or "node needs no repair", end heapify
|
||||
if (p < 0 || this.maxHeap[i] <= this.maxHeap[p]) break;
|
||||
// Swap two nodes
|
||||
this.swap(i, p);
|
||||
// Loop upward heapify
|
||||
i = p;
|
||||
}
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
public pop(): number {
|
||||
// Handle empty case
|
||||
if (this.isEmpty()) throw new RangeError('Heap is empty.');
|
||||
// Delete node
|
||||
this.swap(0, this.size() - 1);
|
||||
// Remove node
|
||||
const val = this.maxHeap.pop();
|
||||
// Return top element
|
||||
this.siftDown(0);
|
||||
// Return heap top element
|
||||
return val;
|
||||
}
|
||||
|
||||
/* Starting from node i, heapify from top to bottom */
|
||||
private siftDown(i: number): void {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
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;
|
||||
// Swap two nodes
|
||||
if (ma === i) break;
|
||||
// Swap two nodes
|
||||
this.swap(i, ma);
|
||||
// Loop downwards heapification
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
public print(): void {
|
||||
printHeap(this.maxHeap);
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
public getMaxHeap(): number[] {
|
||||
return this.maxHeap;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
if (import.meta.url.endsWith(process.argv[1])) {
|
||||
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
|
||||
const maxHeap = new MaxHeap([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
|
||||
console.log('\nAfter inputting list and building heap');
|
||||
maxHeap.print();
|
||||
|
||||
/* Check if heap is empty */
|
||||
let peek = maxHeap.peek();
|
||||
console.log(`\nHeap top element is ${peek}`);
|
||||
|
||||
/* Element enters heap */
|
||||
const val = 7;
|
||||
maxHeap.push(val);
|
||||
console.log(`\nAfter element ${val} pushes to heap`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Time complexity is O(n), not O(nlogn) */
|
||||
peek = maxHeap.pop();
|
||||
console.log(`\nAfter heap top element ${peek} pops from heap`);
|
||||
maxHeap.print();
|
||||
|
||||
/* Get heap size */
|
||||
const size = maxHeap.size();
|
||||
console.log(`\nHeap size is ${size}`);
|
||||
|
||||
/* Check if heap is empty */
|
||||
const isEmpty = maxHeap.isEmpty();
|
||||
console.log(`\nIs heap empty ${isEmpty}`);
|
||||
}
|
||||
|
||||
export { MaxHeap };
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* File: top_k.ts
|
||||
* Created Time: 2023-08-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { MaxHeap } from './my_heap';
|
||||
|
||||
/* Element enters heap */
|
||||
function pushMinHeap(maxHeap: MaxHeap, val: number): void {
|
||||
// Negate element
|
||||
maxHeap.push(-val);
|
||||
}
|
||||
|
||||
/* Element exits heap */
|
||||
function popMinHeap(maxHeap: MaxHeap): number {
|
||||
// Negate element
|
||||
return -maxHeap.pop();
|
||||
}
|
||||
|
||||
/* Access top element */
|
||||
function peekMinHeap(maxHeap: MaxHeap): number {
|
||||
// Negate element
|
||||
return -maxHeap.peek();
|
||||
}
|
||||
|
||||
/* Extract elements from heap */
|
||||
function getMinHeap(maxHeap: MaxHeap): number[] {
|
||||
// Negate element
|
||||
return maxHeap.getMaxHeap().map((num: number) => -num);
|
||||
}
|
||||
|
||||
/* Find the largest k elements in array based on heap */
|
||||
function topKHeap(nums: number[], k: number): number[] {
|
||||
// Python's heapq module implements min heap by default
|
||||
// Note: We negate all heap elements to simulate min heap using max heap
|
||||
const maxHeap = new MaxHeap([]);
|
||||
// Enter the first k elements of array into heap
|
||||
for (let i = 0; i < k; i++) {
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
// Starting from the (k+1)th element, maintain heap length as k
|
||||
for (let i = k; i < nums.length; i++) {
|
||||
// If current element is greater than top element, top element exits heap, current element enters heap
|
||||
if (nums[i] > peekMinHeap(maxHeap)) {
|
||||
popMinHeap(maxHeap);
|
||||
pushMinHeap(maxHeap, nums[i]);
|
||||
}
|
||||
}
|
||||
// Return elements in heap
|
||||
return getMinHeap(maxHeap);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [1, 7, 6, 3, 2];
|
||||
const k = 3;
|
||||
const res = topKHeap(nums, k);
|
||||
console.log(`The largest ${k} elements are`, res);
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* File: binary_search.ts
|
||||
* Created Time: 2022-12-27
|
||||
* Author: Daniel (better.sunjian@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
function binarySearch(nums: number[], target: number): number {
|
||||
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
|
||||
let i = 0,
|
||||
j = nums.length - 1;
|
||||
// Loop, exit when the search interval is empty (empty when i > j)
|
||||
while (i <= j) {
|
||||
// Calculate the midpoint index m
|
||||
const m = Math.floor(i + (j - i) / 2);
|
||||
if (nums[m] < target) {
|
||||
// This means target is in the interval [m+1, j]
|
||||
i = m + 1;
|
||||
} else if (nums[m] > target) {
|
||||
// This means target is in the interval [i, m-1]
|
||||
j = m - 1;
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return -1; // Target element not found, return -1
|
||||
}
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
function binarySearchLCRO(nums: number[], target: number): number {
|
||||
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
|
||||
let i = 0,
|
||||
j = nums.length;
|
||||
// Loop, exit when the search interval is empty (empty when i = j)
|
||||
while (i < j) {
|
||||
// Calculate the midpoint index m
|
||||
const m = Math.floor(i + (j - i) / 2);
|
||||
if (nums[m] < target) {
|
||||
// This means target is in the interval [m+1, j)
|
||||
i = m + 1;
|
||||
} else if (nums[m] > target) {
|
||||
// This means target is in the interval [i, m)
|
||||
j = m;
|
||||
} else {
|
||||
// Found the target element, return its index
|
||||
return m;
|
||||
}
|
||||
}
|
||||
return -1; // Target element not found, return -1
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const target = 6;
|
||||
const nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
|
||||
/* Binary search (closed interval on both sides) */
|
||||
let index = binarySearch(nums, target);
|
||||
console.info('Index of target element 6 is %d', index);
|
||||
|
||||
/* Binary search (left-closed right-open interval) */
|
||||
index = binarySearchLCRO(nums, target);
|
||||
console.info('Index of target element 6 is %d', index);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: binary_search_edge.ts
|
||||
* Created Time: 2023-08-22
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
import { binarySearchInsertion } from './binary_search_insertion';
|
||||
|
||||
/* Binary search for the leftmost target */
|
||||
function binarySearchLeftEdge(nums: Array<number>, target: number): number {
|
||||
// Equivalent to finding the insertion point of target
|
||||
const i = binarySearchInsertion(nums, target);
|
||||
// Target not found, return -1
|
||||
if (i === nums.length || nums[i] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for the rightmost target */
|
||||
function binarySearchRightEdge(nums: Array<number>, target: number): number {
|
||||
// Convert to finding the leftmost target + 1
|
||||
const i = binarySearchInsertion(nums, target + 1);
|
||||
// j points to the rightmost target, i points to the first element greater than target
|
||||
const j = i - 1;
|
||||
// Target not found, return -1
|
||||
if (j === -1 || nums[j] !== target) {
|
||||
return -1;
|
||||
}
|
||||
// Found target, return index j
|
||||
return j;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Array with duplicate elements
|
||||
let nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search left and right boundaries
|
||||
for (const target of [6, 7]) {
|
||||
let index = binarySearchLeftEdge(nums, target);
|
||||
console.log('Leftmost element ' + target + ' has index ' + index);
|
||||
index = binarySearchRightEdge(nums, target);
|
||||
console.log('Rightmost element ' + target + ' has index ' + index);
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* File: binary_search_insertion.ts
|
||||
* Created Time: 2023-08-22
|
||||
* Author: Gaofer Chou (gaofer-chou@qq.com)
|
||||
*/
|
||||
|
||||
/* Binary search for insertion point (no duplicate elements) */
|
||||
function binarySearchInsertionSimple(
|
||||
nums: Array<number>,
|
||||
target: number
|
||||
): number {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // Initialize closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, use Math.floor() to round down
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
} else {
|
||||
return m; // Found target, return insertion point m
|
||||
}
|
||||
}
|
||||
// Target not found, return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Binary search for insertion point (with duplicate elements) */
|
||||
function binarySearchInsertion(nums: Array<number>, target: number): number {
|
||||
let i = 0,
|
||||
j = nums.length - 1; // Initialize closed interval [0, n-1]
|
||||
while (i <= j) {
|
||||
const m = Math.floor(i + (j - i) / 2); // Calculate midpoint index m, use Math.floor() to round down
|
||||
if (nums[m] < target) {
|
||||
i = m + 1; // target is in the interval [m+1, j]
|
||||
} else if (nums[m] > target) {
|
||||
j = m - 1; // target is in the interval [i, m-1]
|
||||
} else {
|
||||
j = m - 1; // The first element less than target is in the interval [i, m-1]
|
||||
}
|
||||
}
|
||||
// Return insertion point i
|
||||
return i;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Array without duplicate elements
|
||||
let nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search for insertion point
|
||||
for (const target of [6, 9]) {
|
||||
const index = binarySearchInsertionSimple(nums, target);
|
||||
console.log('Element ' + target + ''s insertion point index is ' + index);
|
||||
}
|
||||
|
||||
// Array with duplicate elements
|
||||
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
|
||||
console.log('\nArray nums = ' + nums);
|
||||
// Binary search for insertion point
|
||||
for (const target of [2, 6, 20]) {
|
||||
const index = binarySearchInsertion(nums, target);
|
||||
console.log('Element ' + target + ''s insertion point index is ' + index);
|
||||
}
|
||||
|
||||
export { binarySearchInsertion };
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* File: hashing_search.ts
|
||||
* Created Time: 2022-12-29
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
import { ListNode, arrToLinkedList } from '../modules/ListNode';
|
||||
|
||||
/* Hash search (array) */
|
||||
function hashingSearchArray(map: Map<number, number>, target: number): number {
|
||||
// Hash table's key: target element, value: index
|
||||
// If this key does not exist in the hash table, return -1
|
||||
return map.has(target) ? (map.get(target) as number) : -1;
|
||||
}
|
||||
|
||||
/* Hash search (linked list) */
|
||||
function hashingSearchLinkedList(
|
||||
map: Map<number, ListNode>,
|
||||
target: number
|
||||
): ListNode | null {
|
||||
// Hash table key: target node value, value: node object
|
||||
// If key is not in hash table, return null
|
||||
return map.has(target) ? (map.get(target) as ListNode) : null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const target = 3;
|
||||
|
||||
/* Hash search (array) */
|
||||
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
// Initialize hash table
|
||||
const map = new Map();
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
map.set(nums[i], i); // key: element, value: index
|
||||
}
|
||||
const index = hashingSearchArray(map, target);
|
||||
console.log('Index of target element 3 = ' + index);
|
||||
|
||||
/* Hash search (linked list) */
|
||||
let head = arrToLinkedList(nums);
|
||||
// Initialize hash table
|
||||
const map1 = new Map();
|
||||
while (head != null) {
|
||||
map1.set(head.val, head); // key: node value, value: node
|
||||
head = head.next;
|
||||
}
|
||||
const node = hashingSearchLinkedList(map1, target);
|
||||
console.log('Node object with target value 3 is', node);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* File: linear_search.ts
|
||||
* Created Time: 2023-01-07
|
||||
* Author: Daniel (better.sunjian@gmail.com)
|
||||
*/
|
||||
|
||||
import { ListNode, arrToLinkedList } from '../modules/ListNode';
|
||||
|
||||
/* Linear search (array) */
|
||||
function linearSearchArray(nums: number[], target: number): number {
|
||||
// Traverse array
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
// Found the target element, return its index
|
||||
if (nums[i] === target) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
// Target element not found, return -1
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* Linear search (linked list) */
|
||||
function linearSearchLinkedList(
|
||||
head: ListNode | null,
|
||||
target: number
|
||||
): ListNode | null {
|
||||
// Traverse the linked list
|
||||
while (head) {
|
||||
// Found the target node, return it
|
||||
if (head.val === target) {
|
||||
return head;
|
||||
}
|
||||
head = head.next;
|
||||
}
|
||||
// Target node not found, return null
|
||||
return null;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const target = 3;
|
||||
|
||||
/* Perform linear search in array */
|
||||
const nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
|
||||
const index = linearSearchArray(nums, target);
|
||||
console.log('Index of target element 3 =', index);
|
||||
|
||||
/* Perform linear search in linked list */
|
||||
const head = arrToLinkedList(nums);
|
||||
const node = linearSearchLinkedList(head, target);
|
||||
console.log('Node object with target value 3 is', node);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,49 @@
|
||||
/**
|
||||
* File: two_sum.ts
|
||||
* Created Time: 2022-12-15
|
||||
* Author: gyt95 (gytkwan@gmail.com)
|
||||
*/
|
||||
|
||||
/* Method 1: Brute force enumeration */
|
||||
function twoSumBruteForce(nums: number[], target: number): number[] {
|
||||
const n = nums.length;
|
||||
// Two nested loops, time complexity is 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 [];
|
||||
}
|
||||
|
||||
/* Method 2: Auxiliary hash table */
|
||||
function twoSumHashTable(nums: number[], target: number): number[] {
|
||||
// Auxiliary hash table, space complexity is O(n)
|
||||
let m: Map<number, number> = new Map();
|
||||
// Single loop, time complexity is O(n)
|
||||
for (let i = 0; i < nums.length; i++) {
|
||||
let index = m.get(target - nums[i]);
|
||||
if (index !== undefined) {
|
||||
return [index, i];
|
||||
} else {
|
||||
m.set(nums[i], i);
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Method 1
|
||||
const nums = [2, 7, 11, 15],
|
||||
target = 13;
|
||||
|
||||
let res = twoSumBruteForce(nums, target);
|
||||
console.log('Method 1 res = ', res);
|
||||
|
||||
// Method 2
|
||||
res = twoSumHashTable(nums, target);
|
||||
console.log('Method 2 res = ', res);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: bubble_sort.ts
|
||||
* Created Time: 2022-12-12
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Bubble sort */
|
||||
function bubbleSort(nums: number[]): void {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Bubble sort (flag optimization) */
|
||||
function bubbleSortWithFlag(nums: number[]): void {
|
||||
// Outer loop: unsorted range is [0, i]
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
let flag = false; // Initialize flag
|
||||
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
|
||||
for (let j = 0; j < i; j++) {
|
||||
if (nums[j] > nums[j + 1]) {
|
||||
// Swap nums[j] and nums[j + 1]
|
||||
let tmp = nums[j];
|
||||
nums[j] = nums[j + 1];
|
||||
nums[j + 1] = tmp;
|
||||
flag = true; // Record element swap
|
||||
}
|
||||
}
|
||||
if (!flag) break; // No elements were swapped in this round of "bubbling", exit directly
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSort(nums);
|
||||
console.log('After bubble sort, nums =', nums);
|
||||
|
||||
const nums1 = [4, 1, 3, 1, 5, 2];
|
||||
bubbleSortWithFlag(nums1);
|
||||
console.log('After bubble sort, nums =', nums1);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: bucket_sort.ts
|
||||
* Created Time: 2023-04-08
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Bucket sort */
|
||||
function bucketSort(nums: number[]): void {
|
||||
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
|
||||
const k = nums.length / 2;
|
||||
const buckets: number[][] = [];
|
||||
for (let i = 0; i < k; i++) {
|
||||
buckets.push([]);
|
||||
}
|
||||
// 1. Distribute array elements into various buckets
|
||||
for (const num of nums) {
|
||||
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
|
||||
const i = Math.floor(num * k);
|
||||
// Add num to bucket i
|
||||
buckets[i].push(num);
|
||||
}
|
||||
// 2. Sort each bucket
|
||||
for (const bucket of buckets) {
|
||||
// Use built-in sorting function, can also replace with other sorting algorithms
|
||||
bucket.sort((a, b) => a - b);
|
||||
}
|
||||
// 3. Traverse buckets to merge results
|
||||
let i = 0;
|
||||
for (const bucket of buckets) {
|
||||
for (const num of bucket) {
|
||||
nums[i++] = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
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('After bucket sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* File: counting_sort.ts
|
||||
* Created Time: 2023-04-08
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Counting sort */
|
||||
// Simple implementation, cannot be used for sorting objects
|
||||
function countingSortNaive(nums: number[]): void {
|
||||
// 1. Count the maximum element m in the array
|
||||
let m: number = Math.max(...nums);
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
const counter: number[] = new Array<number>(m + 1).fill(0);
|
||||
for (const num of nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Traverse counter, filling each element back into the original array nums
|
||||
let i = 0;
|
||||
for (let num = 0; num < m + 1; num++) {
|
||||
for (let j = 0; j < counter[num]; j++, i++) {
|
||||
nums[i] = num;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Counting sort */
|
||||
// Complete implementation, can sort objects and is a stable sort
|
||||
function countingSort(nums: number[]): void {
|
||||
// 1. Count the maximum element m in the array
|
||||
let m: number = Math.max(...nums);
|
||||
// 2. Count the occurrence of each number
|
||||
// counter[num] represents the occurrence of num
|
||||
const counter: number[] = new Array<number>(m + 1).fill(0);
|
||||
for (const num of nums) {
|
||||
counter[num]++;
|
||||
}
|
||||
// 3. Calculate the prefix sum of counter, converting "occurrence count" to "tail index"
|
||||
// counter[num]-1 is the last index where num appears in res
|
||||
for (let i = 0; i < m; i++) {
|
||||
counter[i + 1] += counter[i];
|
||||
}
|
||||
// 4. Traverse nums in reverse order, placing each element into the result array res
|
||||
// Initialize the array res to record results
|
||||
const n = nums.length;
|
||||
const res: number[] = new Array<number>(n);
|
||||
for (let i = n - 1; i >= 0; i--) {
|
||||
const num = nums[i];
|
||||
res[counter[num] - 1] = num; // Place num at the corresponding index
|
||||
counter[num]--; // Decrement the prefix sum by 1, getting the next index to place num
|
||||
}
|
||||
// Use result array res to overwrite the original array nums
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
countingSortNaive(nums);
|
||||
console.log('After counting sort (cannot sort objects), nums =', nums);
|
||||
|
||||
const nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
|
||||
countingSort(nums1);
|
||||
console.log('After counting sort, nums1 =', nums1);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* File: heap_sort.ts
|
||||
* Created Time: 2023-06-04
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Heap length is n, start heapifying node i, from top to bottom */
|
||||
function siftDown(nums: number[], n: number, i: number): void {
|
||||
while (true) {
|
||||
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
|
||||
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;
|
||||
}
|
||||
// Swap two nodes
|
||||
if (ma === i) {
|
||||
break;
|
||||
}
|
||||
// Swap two nodes
|
||||
[nums[i], nums[ma]] = [nums[ma], nums[i]];
|
||||
// Loop downwards heapification
|
||||
i = ma;
|
||||
}
|
||||
}
|
||||
|
||||
/* Heap sort */
|
||||
function heapSort(nums: number[]): void {
|
||||
// Build heap operation: heapify all nodes except leaves
|
||||
for (let i = Math.floor(nums.length / 2) - 1; i >= 0; i--) {
|
||||
siftDown(nums, nums.length, i);
|
||||
}
|
||||
// Extract the largest element from the heap and repeat for n-1 rounds
|
||||
for (let i = nums.length - 1; i > 0; i--) {
|
||||
// Delete node
|
||||
[nums[0], nums[i]] = [nums[i], nums[0]];
|
||||
// Start heapifying the root node, from top to bottom
|
||||
siftDown(nums, i, 0);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums: number[] = [4, 1, 3, 1, 5, 2];
|
||||
heapSort(nums);
|
||||
console.log('After heap sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* File: insertion_sort.ts
|
||||
* Created Time: 2022-12-12
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Insertion sort */
|
||||
function insertionSort(nums: number[]): void {
|
||||
// Outer loop: sorted interval is [0, i-1]
|
||||
for (let i = 1; i < nums.length; i++) {
|
||||
const base = nums[i];
|
||||
let j = i - 1;
|
||||
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
|
||||
while (j >= 0 && nums[j] > base) {
|
||||
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
|
||||
j--;
|
||||
}
|
||||
nums[j + 1] = base; // Assign base to the correct position
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [4, 1, 3, 1, 5, 2];
|
||||
insertionSort(nums);
|
||||
console.log('After insertion sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,54 @@
|
||||
/**
|
||||
* File: merge_sort.ts
|
||||
* Created Time: 2022-12-12
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Merge left subarray and right subarray */
|
||||
function merge(nums: number[], left: number, mid: number, right: number): void {
|
||||
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
|
||||
// Create a temporary array tmp to store the merged results
|
||||
const tmp = new Array(right - left + 1);
|
||||
// Initialize the start indices of the left and right subarrays
|
||||
let i = left,
|
||||
j = mid + 1,
|
||||
k = 0;
|
||||
// While both subarrays still have elements, compare and copy the smaller element into the temporary array
|
||||
while (i <= mid && j <= right) {
|
||||
if (nums[i] <= nums[j]) {
|
||||
tmp[k++] = nums[i++];
|
||||
} else {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
}
|
||||
// Copy the remaining elements of the left and right subarrays into the temporary array
|
||||
while (i <= mid) {
|
||||
tmp[k++] = nums[i++];
|
||||
}
|
||||
while (j <= right) {
|
||||
tmp[k++] = nums[j++];
|
||||
}
|
||||
// Copy the elements from the temporary array tmp back to the original array nums at the corresponding interval
|
||||
for (k = 0; k < tmp.length; k++) {
|
||||
nums[left + k] = tmp[k];
|
||||
}
|
||||
}
|
||||
|
||||
/* Merge sort */
|
||||
function mergeSort(nums: number[], left: number, right: number): void {
|
||||
// Termination condition
|
||||
if (left >= right) return; // Terminate recursion when subarray length is 1
|
||||
// Divide and conquer stage
|
||||
let mid = Math.floor(left + (right - left) / 2); // Calculate midpoint
|
||||
mergeSort(nums, left, mid); // Recursively process the left subarray
|
||||
mergeSort(nums, mid + 1, right); // Recursively process the right subarray
|
||||
// Merge stage
|
||||
merge(nums, left, mid, right);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [7, 3, 2, 6, 0, 1, 5, 4];
|
||||
mergeSort(nums, 0, nums.length - 1);
|
||||
console.log('After merge sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,180 @@
|
||||
/**
|
||||
* File: quick_sort.ts
|
||||
* Created Time: 2022-12-12
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Quick sort class */
|
||||
class QuickSort {
|
||||
/* Swap elements */
|
||||
swap(nums: number[], i: number, j: number): void {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
partition(nums: number[], left: number, right: number): number {
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) {
|
||||
j -= 1; // Search from right to left for the first element smaller than the pivot
|
||||
}
|
||||
while (i < j && nums[i] <= nums[left]) {
|
||||
i += 1; // Search from left to right for the first element greater than the pivot
|
||||
}
|
||||
// Swap elements
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
quickSort(nums: number[], left: number, right: number): void {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if (left >= right) {
|
||||
return;
|
||||
}
|
||||
// Sentinel partition
|
||||
const pivot = this.partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
this.quickSort(nums, left, pivot - 1);
|
||||
this.quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quick sort class (median pivot optimization) */
|
||||
class QuickSortMedian {
|
||||
/* Swap elements */
|
||||
swap(nums: number[], i: number, j: number): void {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Select the median of three candidate elements */
|
||||
medianThree(
|
||||
nums: number[],
|
||||
left: number,
|
||||
mid: number,
|
||||
right: number
|
||||
): number {
|
||||
let l = nums[left],
|
||||
m = nums[mid],
|
||||
r = nums[right];
|
||||
// m is between l and r
|
||||
if ((l <= m && m <= r) || (r <= m && m <= l)) return mid;
|
||||
// l is between m and r
|
||||
if ((m <= l && l <= r) || (r <= l && l <= m)) return left;
|
||||
return right;
|
||||
}
|
||||
|
||||
/* Sentinel partition (median of three) */
|
||||
partition(nums: number[], left: number, right: number): number {
|
||||
// Select the median of three candidate elements
|
||||
let med = this.medianThree(
|
||||
nums,
|
||||
left,
|
||||
Math.floor((left + right) / 2),
|
||||
right
|
||||
);
|
||||
// Swap the median to the array's leftmost position
|
||||
this.swap(nums, left, med);
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) {
|
||||
j--; // Search from right to left for the first element smaller than the pivot
|
||||
}
|
||||
while (i < j && nums[i] <= nums[left]) {
|
||||
i++; // Search from left to right for the first element greater than the pivot
|
||||
}
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort */
|
||||
quickSort(nums: number[], left: number, right: number): void {
|
||||
// Terminate recursion when subarray length is 1
|
||||
if (left >= right) {
|
||||
return;
|
||||
}
|
||||
// Sentinel partition
|
||||
const pivot = this.partition(nums, left, right);
|
||||
// Recursively process the left subarray and right subarray
|
||||
this.quickSort(nums, left, pivot - 1);
|
||||
this.quickSort(nums, pivot + 1, right);
|
||||
}
|
||||
}
|
||||
|
||||
/* Quick sort class (recursion depth optimization) */
|
||||
class QuickSortTailCall {
|
||||
/* Swap elements */
|
||||
swap(nums: number[], i: number, j: number): void {
|
||||
let tmp = nums[i];
|
||||
nums[i] = nums[j];
|
||||
nums[j] = tmp;
|
||||
}
|
||||
|
||||
/* Sentinel partition */
|
||||
partition(nums: number[], left: number, right: number): number {
|
||||
// Use nums[left] as the pivot
|
||||
let i = left,
|
||||
j = right;
|
||||
while (i < j) {
|
||||
while (i < j && nums[j] >= nums[left]) {
|
||||
j--; // Search from right to left for the first element smaller than the pivot
|
||||
}
|
||||
while (i < j && nums[i] <= nums[left]) {
|
||||
i++; // Search from left to right for the first element greater than the pivot
|
||||
}
|
||||
this.swap(nums, i, j); // Swap these two elements
|
||||
}
|
||||
this.swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
|
||||
return i; // Return the index of the pivot
|
||||
}
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
quickSort(nums: number[], left: number, right: number): void {
|
||||
// Terminate when subarray length is 1
|
||||
while (left < right) {
|
||||
// Sentinel partition operation
|
||||
let pivot = this.partition(nums, left, right);
|
||||
// Perform quick sort on the shorter of the two subarrays
|
||||
if (pivot - left < right - pivot) {
|
||||
this.quickSort(nums, left, pivot - 1); // Recursively sort the left subarray
|
||||
left = pivot + 1; // Remaining unsorted interval is [pivot + 1, right]
|
||||
} else {
|
||||
this.quickSort(nums, pivot + 1, right); // Recursively sort the right subarray
|
||||
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Quick sort */
|
||||
const nums = [2, 4, 1, 0, 3, 5];
|
||||
const quickSort = new QuickSort();
|
||||
quickSort.quickSort(nums, 0, nums.length - 1);
|
||||
console.log('After quick sort, nums =', nums);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
const nums1 = [2, 4, 1, 0, 3, 5];
|
||||
const quickSortMedian = new QuickSortMedian();
|
||||
quickSortMedian.quickSort(nums1, 0, nums1.length - 1);
|
||||
console.log('After quick sort (median pivot optimization), nums =', nums1);
|
||||
|
||||
/* Quick sort (recursion depth optimization) */
|
||||
const nums2 = [2, 4, 1, 0, 3, 5];
|
||||
const quickSortTailCall = new QuickSortTailCall();
|
||||
quickSortTailCall.quickSort(nums2, 0, nums2.length - 1);
|
||||
console.log('After quick sort (recursion depth optimization), nums =', nums2);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,63 @@
|
||||
/**
|
||||
* File: radix_sort.ts
|
||||
* Created Time: 2023-04-08
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Get the k-th digit of element num, where exp = 10^(k-1) */
|
||||
function digit(num: number, exp: number): number {
|
||||
// Passing exp instead of k can avoid repeated expensive exponentiation here
|
||||
return Math.floor(num / exp) % 10;
|
||||
}
|
||||
|
||||
/* Counting sort (based on nums k-th digit) */
|
||||
function countingSortDigit(nums: number[], exp: number): void {
|
||||
// Decimal digit range is 0~9, therefore need a bucket array of length 10
|
||||
const counter = new Array(10).fill(0);
|
||||
const n = nums.length;
|
||||
// Count the occurrence of digits 0~9
|
||||
for (let i = 0; i < n; i++) {
|
||||
const d = digit(nums[i], exp); // Get the k-th digit of nums[i], noted as d
|
||||
counter[d]++; // Count the occurrence of digit d
|
||||
}
|
||||
// Calculate prefix sum, converting "occurrence count" into "array index"
|
||||
for (let i = 1; i < 10; i++) {
|
||||
counter[i] += counter[i - 1];
|
||||
}
|
||||
// Traverse in reverse, based on bucket statistics, place each element into 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; // Get the index j for d in the array
|
||||
res[j] = nums[i]; // Place the current element at index j
|
||||
counter[d]--; // Decrease the count of d by 1
|
||||
}
|
||||
// Use result to overwrite the original array nums
|
||||
for (let i = 0; i < n; i++) {
|
||||
nums[i] = res[i];
|
||||
}
|
||||
}
|
||||
|
||||
/* Radix sort */
|
||||
function radixSort(nums: number[]): void {
|
||||
// Get the maximum element of the array, used to determine the maximum number of digits
|
||||
let m: number = Math.max(... nums);
|
||||
// Traverse from the lowest to the highest digit
|
||||
for (let exp = 1; exp <= m; exp *= 10) {
|
||||
// Perform counting sort on the k-th digit of array elements
|
||||
// k = 1 -> exp = 1
|
||||
// k = 2 -> exp = 10
|
||||
// i.e., exp = 10^(k-1)
|
||||
countingSortDigit(nums, exp);
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums = [
|
||||
10546151, 35663510, 42865989, 34862445, 81883077, 88906420, 72429244,
|
||||
30524779, 82060337, 63832996,
|
||||
];
|
||||
radixSort(nums);
|
||||
console.log('After radix sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,29 @@
|
||||
/**
|
||||
* File: selection_sort.ts
|
||||
* Created Time: 2023-06-04
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Selection sort */
|
||||
function selectionSort(nums: number[]): void {
|
||||
let n = nums.length;
|
||||
// Outer loop: unsorted interval is [i, n-1]
|
||||
for (let i = 0; i < n - 1; i++) {
|
||||
// Inner loop: find the smallest element within the unsorted interval
|
||||
let k = i;
|
||||
for (let j = i + 1; j < n; j++) {
|
||||
if (nums[j] < nums[k]) {
|
||||
k = j; // Record the index of the smallest element
|
||||
}
|
||||
}
|
||||
// Swap the smallest element with the first element of the unsorted interval
|
||||
[nums[i], nums[k]] = [nums[k], nums[i]];
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
const nums: number[] = [4, 1, 3, 1, 5, 2];
|
||||
selectionSort(nums);
|
||||
console.log('After selection sort, nums =', nums);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* File: array_deque.ts
|
||||
* Created Time: 2023-02-28
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Double-ended queue based on circular array implementation */
|
||||
class ArrayDeque {
|
||||
private nums: number[]; // Array for storing double-ended queue elements
|
||||
private front: number; // Front pointer, points to the front of the queue element
|
||||
private queSize: number; // Double-ended queue length
|
||||
|
||||
/* Constructor */
|
||||
constructor(capacity: number) {
|
||||
this.nums = new Array(capacity);
|
||||
this.front = 0;
|
||||
this.queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the double-ended queue */
|
||||
capacity(): number {
|
||||
return this.nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
size(): number {
|
||||
return this.queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.queSize === 0;
|
||||
}
|
||||
|
||||
/* Calculate circular array index */
|
||||
index(i: number): number {
|
||||
// Use modulo operation to wrap the array head and tail together
|
||||
// When i passes the tail of the array, return to the head
|
||||
// When i passes the head of the array, return to the tail
|
||||
return (i + this.capacity()) % this.capacity();
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue */
|
||||
pushFirst(num: number): void {
|
||||
if (this.queSize === this.capacity()) {
|
||||
console.log('Double-ended queue is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap front around to the tail after passing the head of the array
|
||||
// Add num to the front of the queue
|
||||
this.front = this.index(this.front - 1);
|
||||
// Add num to front of queue
|
||||
this.nums[this.front] = num;
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue */
|
||||
pushLast(num: number): void {
|
||||
if (this.queSize === this.capacity()) {
|
||||
console.log('Double-ended queue is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
const rear: number = this.index(this.front + this.queSize);
|
||||
// Front pointer moves one position backward
|
||||
this.nums[rear] = num;
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Rear of the queue dequeue */
|
||||
popFirst(): number {
|
||||
const num: number = this.peekFirst();
|
||||
// Move front pointer backward by one position
|
||||
this.front = this.index(this.front + 1);
|
||||
this.queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Access rear of the queue element */
|
||||
popLast(): number {
|
||||
const num: number = this.peekLast();
|
||||
this.queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
peekFirst(): number {
|
||||
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
|
||||
return this.nums[this.front];
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
peekLast(): number {
|
||||
if (this.isEmpty()) throw new Error('The Deque Is Empty.');
|
||||
// Initialize double-ended queue
|
||||
const last = this.index(this.front + this.queSize - 1);
|
||||
return this.nums[last];
|
||||
}
|
||||
|
||||
/* Return array for printing */
|
||||
toArray(): number[] {
|
||||
// Elements enqueue
|
||||
const res: number[] = [];
|
||||
for (let i = 0, j = this.front; i < this.queSize; i++, j++) {
|
||||
res[i] = this.nums[this.index(j)];
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
const capacity = 5;
|
||||
const deque: ArrayDeque = new ArrayDeque(capacity);
|
||||
deque.pushLast(3);
|
||||
deque.pushLast(2);
|
||||
deque.pushLast(5);
|
||||
console.log('Deque deque = [' + deque.toArray() + ']');
|
||||
|
||||
/* Update element */
|
||||
const peekFirst = deque.peekFirst();
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast = deque.peekLast();
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.pushLast(4);
|
||||
console.log('After element 4 enqueues at rear, deque = [' + deque.toArray() + ']');
|
||||
deque.pushFirst(1);
|
||||
console.log('After element 1 enqueues at front, deque = [' + deque.toArray() + ']');
|
||||
|
||||
/* Element dequeue */
|
||||
const popLast = deque.popLast();
|
||||
console.log(
|
||||
'Rear dequeue element = ' +
|
||||
popLast +
|
||||
', after rear dequeue deque = [' +
|
||||
deque.toArray() +
|
||||
']'
|
||||
);
|
||||
const popFirst = deque.popFirst();
|
||||
console.log(
|
||||
'Front dequeue element = ' +
|
||||
popFirst +
|
||||
', after front dequeue deque = [' +
|
||||
deque.toArray() +
|
||||
']'
|
||||
);
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
const size = deque.size();
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
const isEmpty = deque.isEmpty();
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,109 @@
|
||||
/**
|
||||
* File: array_queue.ts
|
||||
* Created Time: 2022-12-11
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Queue based on circular array implementation */
|
||||
class ArrayQueue {
|
||||
private nums: number[]; // Array for storing queue elements
|
||||
private front: number; // Front pointer, points to the front of the queue element
|
||||
private queSize: number; // Queue length
|
||||
|
||||
constructor(capacity: number) {
|
||||
this.nums = new Array(capacity);
|
||||
this.front = this.queSize = 0;
|
||||
}
|
||||
|
||||
/* Get the capacity of the queue */
|
||||
get capacity(): number {
|
||||
return this.nums.length;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
get size(): number {
|
||||
return this.queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.queSize === 0;
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
push(num: number): void {
|
||||
if (this.size === this.capacity) {
|
||||
console.log('Queue is full');
|
||||
return;
|
||||
}
|
||||
// Use modulo operation to wrap rear around to the head after passing the tail of the array
|
||||
// Add num to the rear of the queue
|
||||
const rear = (this.front + this.queSize) % this.capacity;
|
||||
// Front pointer moves one position backward
|
||||
this.nums[rear] = num;
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
pop(): number {
|
||||
const num = this.peek();
|
||||
// Move front pointer backward by one position, if it passes the tail, return to array head
|
||||
this.front = (this.front + 1) % this.capacity;
|
||||
this.queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
peek(): number {
|
||||
if (this.isEmpty()) throw new Error('Queue is empty');
|
||||
return this.nums[this.front];
|
||||
}
|
||||
|
||||
/* Return Array */
|
||||
toArray(): number[] {
|
||||
// Elements enqueue
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
const capacity = 10;
|
||||
const queue = new ArrayQueue(capacity);
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue =', queue.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
const peek = queue.peek();
|
||||
console.log('Front element peek = ' + peek);
|
||||
|
||||
/* Element dequeue */
|
||||
const pop = queue.pop();
|
||||
console.log('Dequeue element pop = ' + pop + ', after dequeue queue =', queue.toArray());
|
||||
|
||||
/* Get the length of the queue */
|
||||
const size = queue.size;
|
||||
console.log('Queue length size = ' + size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
const isEmpty = queue.isEmpty();
|
||||
console.log('Queue is empty = ' + isEmpty);
|
||||
|
||||
/* Test circular array */
|
||||
for (let i = 0; i < 10; i++) {
|
||||
queue.push(i);
|
||||
queue.pop();
|
||||
console.log('Round ' + i + ' rounds of enqueue + dequeue, queue =', queue.toArray());
|
||||
}
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* File: array_stack.ts
|
||||
* Created Time: 2022-12-08
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Stack based on array implementation */
|
||||
class ArrayStack {
|
||||
private stack: number[];
|
||||
constructor() {
|
||||
this.stack = [];
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
get size(): number {
|
||||
return this.stack.length;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.stack.length === 0;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
push(num: number): void {
|
||||
this.stack.push(num);
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
pop(): number | undefined {
|
||||
if (this.isEmpty()) throw new Error('Stack is empty');
|
||||
return this.stack.pop();
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
top(): number | undefined {
|
||||
if (this.isEmpty()) throw new Error('Stack is empty');
|
||||
return this.stack[this.stack.length - 1];
|
||||
}
|
||||
|
||||
/* Return Array */
|
||||
toArray() {
|
||||
return this.stack;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
const stack = new ArrayStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
console.log('Stack stack = ');
|
||||
console.log(stack.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
const top = stack.top();
|
||||
console.log('Stack top element top = ' + top);
|
||||
|
||||
/* Element pop from stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop = ' + pop + ', after pop, stack = ');
|
||||
console.log(stack.toArray());
|
||||
|
||||
/* Get the length of the stack */
|
||||
const size = stack.size;
|
||||
console.log('Stack length size = ' + size);
|
||||
|
||||
/* Check if empty */
|
||||
const isEmpty = stack.isEmpty();
|
||||
console.log('Stack is empty = ' + isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* File: deque.ts
|
||||
* Created Time: 2023-01-17
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
// TypeScript has no built-in deque, can only use Array as deque
|
||||
const deque: number[] = [];
|
||||
|
||||
/* Elements enqueue */
|
||||
deque.push(2);
|
||||
deque.push(5);
|
||||
deque.push(4);
|
||||
// Note: due to array, unshift() method has O(n) time complexity
|
||||
deque.unshift(3);
|
||||
deque.unshift(1);
|
||||
console.log('Double-ended queue deque = ', deque);
|
||||
|
||||
/* Update element */
|
||||
const peekFirst: number = deque[0];
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast: number = deque[deque.length - 1];
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Element dequeue */
|
||||
// Note: due to array, shift() method has O(n) time complexity
|
||||
const popFront: number = deque.shift() as number;
|
||||
console.log(
|
||||
'Front dequeue element popFront = ' + popFront + ', after front dequeue, deque = ' + deque
|
||||
);
|
||||
const popBack: number = deque.pop() as number;
|
||||
console.log(
|
||||
'Dequeue rear element popBack = ' + popBack + ', after rear dequeue, deque = ' + deque
|
||||
);
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
const size: number = deque.length;
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
const isEmpty: boolean = size === 0;
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* File: linkedlist_deque.ts
|
||||
* Created Time: 2023-02-04
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Doubly linked list node */
|
||||
class ListNode {
|
||||
prev: ListNode; // Predecessor node reference (pointer)
|
||||
next: ListNode; // Successor node reference (pointer)
|
||||
val: number; // Node value
|
||||
|
||||
constructor(val: number) {
|
||||
this.val = val;
|
||||
this.next = null;
|
||||
this.prev = null;
|
||||
}
|
||||
}
|
||||
|
||||
/* Double-ended queue based on doubly linked list implementation */
|
||||
class LinkedListDeque {
|
||||
private front: ListNode; // Head node front
|
||||
private rear: ListNode; // Tail node rear
|
||||
private queSize: number; // Length of the double-ended queue
|
||||
|
||||
constructor() {
|
||||
this.front = null;
|
||||
this.rear = null;
|
||||
this.queSize = 0;
|
||||
}
|
||||
|
||||
/* Rear of the queue enqueue operation */
|
||||
pushLast(val: number): void {
|
||||
const node: ListNode = new ListNode(val);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if (this.queSize === 0) {
|
||||
this.front = node;
|
||||
this.rear = node;
|
||||
} else {
|
||||
// Add node to the tail of the linked list
|
||||
this.rear.next = node;
|
||||
node.prev = this.rear;
|
||||
this.rear = node; // Update tail node
|
||||
}
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Front of the queue enqueue operation */
|
||||
pushFirst(val: number): void {
|
||||
const node: ListNode = new ListNode(val);
|
||||
// If the linked list is empty, make both front and rear point to node
|
||||
if (this.queSize === 0) {
|
||||
this.front = node;
|
||||
this.rear = node;
|
||||
} else {
|
||||
// Add node to the head of the linked list
|
||||
this.front.prev = node;
|
||||
node.next = this.front;
|
||||
this.front = node; // Update head node
|
||||
}
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Temporarily store tail node value */
|
||||
popLast(): number {
|
||||
if (this.queSize === 0) {
|
||||
return null;
|
||||
}
|
||||
const value: number = this.rear.val; // Store tail node value
|
||||
// Update tail node
|
||||
let temp: ListNode = this.rear.prev;
|
||||
if (temp !== null) {
|
||||
temp.next = null;
|
||||
this.rear.prev = null;
|
||||
}
|
||||
this.rear = temp; // Update tail node
|
||||
this.queSize--;
|
||||
return value;
|
||||
}
|
||||
|
||||
/* Temporarily store head node value */
|
||||
popFirst(): number {
|
||||
if (this.queSize === 0) {
|
||||
return null;
|
||||
}
|
||||
const value: number = this.front.val; // Store tail node value
|
||||
// Delete head node
|
||||
let temp: ListNode = this.front.next;
|
||||
if (temp !== null) {
|
||||
temp.prev = null;
|
||||
this.front.next = null;
|
||||
}
|
||||
this.front = temp; // Update head node
|
||||
this.queSize--;
|
||||
return value;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
peekLast(): number {
|
||||
return this.queSize === 0 ? null : this.rear.val;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
peekFirst(): number {
|
||||
return this.queSize === 0 ? null : this.front.val;
|
||||
}
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
size(): number {
|
||||
return this.queSize;
|
||||
}
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.queSize === 0;
|
||||
}
|
||||
|
||||
/* Print deque */
|
||||
print(): void {
|
||||
const arr: number[] = [];
|
||||
let temp: ListNode = this.front;
|
||||
while (temp !== null) {
|
||||
arr.push(temp.val);
|
||||
temp = temp.next;
|
||||
}
|
||||
console.log('[' + arr.join(', ') + ']');
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Get the length of the double-ended queue */
|
||||
const linkedListDeque: LinkedListDeque = new LinkedListDeque();
|
||||
linkedListDeque.pushLast(3);
|
||||
linkedListDeque.pushLast(2);
|
||||
linkedListDeque.pushLast(5);
|
||||
console.log('Deque linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Update element */
|
||||
const peekFirst: number = linkedListDeque.peekFirst();
|
||||
console.log('Front element peekFirst = ' + peekFirst);
|
||||
const peekLast: number = linkedListDeque.peekLast();
|
||||
console.log('Rear element peekLast = ' + peekLast);
|
||||
|
||||
/* Elements enqueue */
|
||||
linkedListDeque.pushLast(4);
|
||||
console.log('After element 4 enqueues at rear, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
linkedListDeque.pushFirst(1);
|
||||
console.log('After element 1 enqueues at front, linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Element dequeue */
|
||||
const popLast: number = linkedListDeque.popLast();
|
||||
console.log('Rear dequeue element = ' + popLast + ', after rear dequeue linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
const popFirst: number = linkedListDeque.popFirst();
|
||||
console.log('Front dequeue element = ' + popFirst + ', after front dequeue linkedListDeque = ');
|
||||
linkedListDeque.print();
|
||||
|
||||
/* Get the length of the double-ended queue */
|
||||
const size: number = linkedListDeque.size();
|
||||
console.log('Double-ended queue length size = ' + size);
|
||||
|
||||
/* Check if the double-ended queue is empty */
|
||||
const isEmpty: boolean = linkedListDeque.isEmpty();
|
||||
console.log('Double-ended queue is empty = ' + isEmpty);
|
||||
@@ -0,0 +1,102 @@
|
||||
/**
|
||||
* File: linkedlist_queue.ts
|
||||
* Created Time: 2022-12-19
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
import { ListNode } from '../modules/ListNode';
|
||||
|
||||
/* Queue based on linked list implementation */
|
||||
class LinkedListQueue {
|
||||
private front: ListNode | null; // Head node front
|
||||
private rear: ListNode | null; // Tail node rear
|
||||
private queSize: number = 0;
|
||||
|
||||
constructor() {
|
||||
this.front = null;
|
||||
this.rear = null;
|
||||
}
|
||||
|
||||
/* Get the length of the queue */
|
||||
get size(): number {
|
||||
return this.queSize;
|
||||
}
|
||||
|
||||
/* Check if the queue is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/* Enqueue */
|
||||
push(num: number): void {
|
||||
// Add num after the tail node
|
||||
const node = new ListNode(num);
|
||||
// If the queue is empty, make both front and rear point to the node
|
||||
if (!this.front) {
|
||||
this.front = node;
|
||||
this.rear = node;
|
||||
// If the queue is not empty, add the node after the tail node
|
||||
} else {
|
||||
this.rear!.next = node;
|
||||
this.rear = node;
|
||||
}
|
||||
this.queSize++;
|
||||
}
|
||||
|
||||
/* Dequeue */
|
||||
pop(): number {
|
||||
const num = this.peek();
|
||||
if (!this.front) throw new Error('Queue is empty');
|
||||
// Delete head node
|
||||
this.front = this.front.next;
|
||||
this.queSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
peek(): number {
|
||||
if (this.size === 0) throw new Error('Queue is empty');
|
||||
return this.front!.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
toArray(): number[] {
|
||||
let node = this.front;
|
||||
const res = new Array<number>(this.size);
|
||||
for (let i = 0; i < res.length; i++) {
|
||||
res[i] = node!.val;
|
||||
node = node!.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
const queue = new LinkedListQueue();
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue = ' + queue.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
const peek = queue.peek();
|
||||
console.log('Front element peek = ' + peek);
|
||||
|
||||
/* Element dequeue */
|
||||
const pop = queue.pop();
|
||||
console.log('Dequeue element pop = ' + pop + ', after dequeue, queue = ' + queue.toArray());
|
||||
|
||||
/* Get the length of the queue */
|
||||
const size = queue.size;
|
||||
console.log('Queue length size = ' + size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
const isEmpty = queue.isEmpty();
|
||||
console.log('Queue is empty = ' + isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* File: linkedlist_stack.ts
|
||||
* Created Time: 2022-12-21
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
import { ListNode } from '../modules/ListNode';
|
||||
|
||||
/* Stack based on linked list implementation */
|
||||
class LinkedListStack {
|
||||
private stackPeek: ListNode | null; // Use head node as stack top
|
||||
private stkSize: number = 0; // Stack length
|
||||
|
||||
constructor() {
|
||||
this.stackPeek = null;
|
||||
}
|
||||
|
||||
/* Get the length of the stack */
|
||||
get size(): number {
|
||||
return this.stkSize;
|
||||
}
|
||||
|
||||
/* Check if the stack is empty */
|
||||
isEmpty(): boolean {
|
||||
return this.size === 0;
|
||||
}
|
||||
|
||||
/* Push */
|
||||
push(num: number): void {
|
||||
const node = new ListNode(num);
|
||||
node.next = this.stackPeek;
|
||||
this.stackPeek = node;
|
||||
this.stkSize++;
|
||||
}
|
||||
|
||||
/* Pop */
|
||||
pop(): number {
|
||||
const num = this.peek();
|
||||
if (!this.stackPeek) throw new Error('Stack is empty');
|
||||
this.stackPeek = this.stackPeek.next;
|
||||
this.stkSize--;
|
||||
return num;
|
||||
}
|
||||
|
||||
/* Return list for printing */
|
||||
peek(): number {
|
||||
if (!this.stackPeek) throw new Error('Stack is empty');
|
||||
return this.stackPeek.val;
|
||||
}
|
||||
|
||||
/* Convert linked list to Array and return */
|
||||
toArray(): number[] {
|
||||
let node = this.stackPeek;
|
||||
const res = new Array<number>(this.size);
|
||||
for (let i = res.length - 1; i >= 0; i--) {
|
||||
res[i] = node!.val;
|
||||
node = node!.next;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
const stack = new LinkedListStack();
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
console.log('Stack stack = ' + stack.toArray());
|
||||
|
||||
/* Return list for printing */
|
||||
const peek = stack.peek();
|
||||
console.log('Stack top element peek = ' + peek);
|
||||
|
||||
/* Element pop from stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop = ' + pop + ', after pop, stack = ' + stack.toArray());
|
||||
|
||||
/* Get the length of the stack */
|
||||
const size = stack.size;
|
||||
console.log('Stack length size = ' + size);
|
||||
|
||||
/* Check if empty */
|
||||
const isEmpty = stack.isEmpty();
|
||||
console.log('Stack is empty = ' + isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: queue.ts
|
||||
* Created Time: 2022-12-05
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Access front of the queue element */
|
||||
// TypeScript has no built-in queue, can use Array as queue
|
||||
const queue: number[] = [];
|
||||
|
||||
/* Elements enqueue */
|
||||
queue.push(1);
|
||||
queue.push(3);
|
||||
queue.push(2);
|
||||
queue.push(5);
|
||||
queue.push(4);
|
||||
console.log('Queue queue =', queue);
|
||||
|
||||
/* Return list for printing */
|
||||
const peek = queue[0];
|
||||
console.log('Front element peek =', peek);
|
||||
|
||||
/* Element dequeue */
|
||||
// Underlying is array, so shift() method has O(n) time complexity
|
||||
const pop = queue.shift();
|
||||
console.log('Dequeue element pop =', pop, ', after dequeue, queue = ', queue);
|
||||
|
||||
/* Get the length of the queue */
|
||||
const size = queue.length;
|
||||
console.log('Queue length size =', size);
|
||||
|
||||
/* Check if the queue is empty */
|
||||
const isEmpty = queue.length === 0;
|
||||
console.log('Queue is empty = ', isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: stack.ts
|
||||
* Created Time: 2022-12-04
|
||||
* Author: S-N-O-R-L-A-X (snorlax.xu@outlook.com)
|
||||
*/
|
||||
|
||||
/* Driver Code */
|
||||
/* Access top of the stack element */
|
||||
// TypeScript has no built-in stack class, can use Array as stack
|
||||
const stack: number[] = [];
|
||||
|
||||
/* Elements push onto stack */
|
||||
stack.push(1);
|
||||
stack.push(3);
|
||||
stack.push(2);
|
||||
stack.push(5);
|
||||
stack.push(4);
|
||||
console.log('Stack stack =', stack);
|
||||
|
||||
/* Return list for printing */
|
||||
const peek = stack[stack.length - 1];
|
||||
console.log('Stack top element peek =', peek);
|
||||
|
||||
/* Element pop from stack */
|
||||
const pop = stack.pop();
|
||||
console.log('Pop element pop =', pop);
|
||||
console.log('After pop, stack =', stack);
|
||||
|
||||
/* Get the length of the stack */
|
||||
const size = stack.length;
|
||||
console.log('Stack length size =', size);
|
||||
|
||||
/* Check if empty */
|
||||
const isEmpty = stack.length === 0;
|
||||
console.log('Is stack empty =', isEmpty);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* File: array_binary_tree.js
|
||||
* Created Time: 2023-08-09
|
||||
* Author: yuan0221 (yl1452491917@gmail.com)
|
||||
*/
|
||||
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
type Order = 'pre' | 'in' | 'post';
|
||||
|
||||
/* Binary tree class represented by array */
|
||||
class ArrayBinaryTree {
|
||||
#tree: (number | null)[];
|
||||
|
||||
/* Constructor */
|
||||
constructor(arr: (number | null)[]) {
|
||||
this.#tree = arr;
|
||||
}
|
||||
|
||||
/* List capacity */
|
||||
size(): number {
|
||||
return this.#tree.length;
|
||||
}
|
||||
|
||||
/* Get value of node at index i */
|
||||
val(i: number): number | null {
|
||||
// If index out of bounds, return null to represent empty position
|
||||
if (i < 0 || i >= this.size()) return null;
|
||||
return this.#tree[i];
|
||||
}
|
||||
|
||||
/* Get index of left child node of node at index i */
|
||||
left(i: number): number {
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
/* Get index of right child node of node at index i */
|
||||
right(i: number): number {
|
||||
return 2 * i + 2;
|
||||
}
|
||||
|
||||
/* Get index of parent node of node at index i */
|
||||
parent(i: number): number {
|
||||
return Math.floor((i - 1) / 2); // Floor division
|
||||
}
|
||||
|
||||
/* Level-order traversal */
|
||||
levelOrder(): number[] {
|
||||
let res = [];
|
||||
// Traverse array directly
|
||||
for (let i = 0; i < this.size(); i++) {
|
||||
if (this.val(i) !== null) res.push(this.val(i));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Depth-first traversal */
|
||||
#dfs(i: number, order: Order, res: (number | null)[]): void {
|
||||
// If empty position, return
|
||||
if (this.val(i) === null) return;
|
||||
// Preorder traversal
|
||||
if (order === 'pre') res.push(this.val(i));
|
||||
this.#dfs(this.left(i), order, res);
|
||||
// Inorder traversal
|
||||
if (order === 'in') res.push(this.val(i));
|
||||
this.#dfs(this.right(i), order, res);
|
||||
// Postorder traversal
|
||||
if (order === 'post') res.push(this.val(i));
|
||||
}
|
||||
|
||||
/* Preorder traversal */
|
||||
preOrder(): (number | null)[] {
|
||||
const res = [];
|
||||
this.#dfs(0, 'pre', res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
inOrder(): (number | null)[] {
|
||||
const res = [];
|
||||
this.#dfs(0, 'in', res);
|
||||
return res;
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
postOrder(): (number | null)[] {
|
||||
const res = [];
|
||||
this.#dfs(0, 'post', res);
|
||||
return res;
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
// Initialize binary tree
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
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('\nInitialize binary tree\n');
|
||||
console.log('Array representation of binary tree:');
|
||||
console.log(arr);
|
||||
console.log('Linked list representation of binary tree:');
|
||||
printTree(root);
|
||||
|
||||
// Binary tree class represented by array
|
||||
const abt = new ArrayBinaryTree(arr);
|
||||
|
||||
// Access node
|
||||
const i = 1;
|
||||
const l = abt.left(i);
|
||||
const r = abt.right(i);
|
||||
const p = abt.parent(i);
|
||||
console.log('\nCurrent node index is ' + i + ', value is ' + abt.val(i));
|
||||
console.log(
|
||||
'Its left child node index is ' + l + ', value is ' + (l === null ? 'null' : abt.val(l))
|
||||
);
|
||||
console.log(
|
||||
'Its right child node index is ' + r + ', value is ' + (r === null ? 'null' : abt.val(r))
|
||||
);
|
||||
console.log(
|
||||
'Its parent node index is ' + p + ', value is ' + (p === null ? 'null' : abt.val(p))
|
||||
);
|
||||
|
||||
// Traverse tree
|
||||
let res = abt.levelOrder();
|
||||
console.log('\nLevel-order traversal is:' + res);
|
||||
res = abt.preOrder();
|
||||
console.log('Preorder traversal is:' + res);
|
||||
res = abt.inOrder();
|
||||
console.log('Inorder traversal is:' + res);
|
||||
res = abt.postOrder();
|
||||
console.log('Postorder traversal is:' + res);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,222 @@
|
||||
/**
|
||||
* File: avl_tree.ts
|
||||
* Created Time: 2023-02-06
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { TreeNode } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* AVL tree */
|
||||
class AVLTree {
|
||||
root: TreeNode;
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
this.root = null; // Root node
|
||||
}
|
||||
|
||||
/* Get node height */
|
||||
height(node: TreeNode): number {
|
||||
// Empty node height is -1, leaf node height is 0
|
||||
return node === null ? -1 : node.height;
|
||||
}
|
||||
|
||||
/* Update node height */
|
||||
private updateHeight(node: TreeNode): void {
|
||||
// Node height equals the height of the tallest subtree + 1
|
||||
node.height =
|
||||
Math.max(this.height(node.left), this.height(node.right)) + 1;
|
||||
}
|
||||
|
||||
/* Get balance factor */
|
||||
balanceFactor(node: TreeNode): number {
|
||||
// Empty node balance factor is 0
|
||||
if (node === null) return 0;
|
||||
// Node balance factor = left subtree height - right subtree height
|
||||
return this.height(node.left) - this.height(node.right);
|
||||
}
|
||||
|
||||
/* Right rotation operation */
|
||||
private rightRotate(node: TreeNode): TreeNode {
|
||||
const child = node.left;
|
||||
const grandChild = child.right;
|
||||
// Using child as pivot, rotate node to the right
|
||||
child.right = node;
|
||||
node.left = grandChild;
|
||||
// Update node height
|
||||
this.updateHeight(node);
|
||||
this.updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Left rotation operation */
|
||||
private leftRotate(node: TreeNode): TreeNode {
|
||||
const child = node.right;
|
||||
const grandChild = child.left;
|
||||
// Using child as pivot, rotate node to the left
|
||||
child.left = node;
|
||||
node.right = grandChild;
|
||||
// Update node height
|
||||
this.updateHeight(node);
|
||||
this.updateHeight(child);
|
||||
// Return root node of subtree after rotation
|
||||
return child;
|
||||
}
|
||||
|
||||
/* Perform rotation operation to restore balance to this subtree */
|
||||
private rotate(node: TreeNode): TreeNode {
|
||||
// Get balance factor of node
|
||||
const balanceFactor = this.balanceFactor(node);
|
||||
// Left-leaning tree
|
||||
if (balanceFactor > 1) {
|
||||
if (this.balanceFactor(node.left) >= 0) {
|
||||
// Right rotation
|
||||
return this.rightRotate(node);
|
||||
} else {
|
||||
// First left rotation then right rotation
|
||||
node.left = this.leftRotate(node.left);
|
||||
return this.rightRotate(node);
|
||||
}
|
||||
}
|
||||
// Right-leaning tree
|
||||
if (balanceFactor < -1) {
|
||||
if (this.balanceFactor(node.right) <= 0) {
|
||||
// Left rotation
|
||||
return this.leftRotate(node);
|
||||
} else {
|
||||
// First right rotation then left rotation
|
||||
node.right = this.rightRotate(node.right);
|
||||
return this.leftRotate(node);
|
||||
}
|
||||
}
|
||||
// Balanced tree, no rotation needed, return directly
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
insert(val: number): void {
|
||||
this.root = this.insertHelper(this.root, val);
|
||||
}
|
||||
|
||||
/* Recursively insert node (helper method) */
|
||||
private insertHelper(node: TreeNode, val: number): TreeNode {
|
||||
if (node === null) return new TreeNode(val);
|
||||
/* 1. Find insertion position and insert node */
|
||||
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; // Duplicate node not inserted, return directly
|
||||
}
|
||||
this.updateHeight(node); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
node = this.rotate(node);
|
||||
// Return root node of subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
remove(val: number): void {
|
||||
this.root = this.removeHelper(this.root, val);
|
||||
}
|
||||
|
||||
/* Recursively delete node (helper method) */
|
||||
private removeHelper(node: TreeNode, val: number): TreeNode {
|
||||
if (node === null) return null;
|
||||
/* 1. Find node and delete */
|
||||
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;
|
||||
// Number of child nodes = 0, delete node directly and return
|
||||
if (child === null) {
|
||||
return null;
|
||||
} else {
|
||||
// Number of child nodes = 1, delete node directly
|
||||
node = child;
|
||||
}
|
||||
} else {
|
||||
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
|
||||
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); // Update node height
|
||||
/* 2. Perform rotation operation to restore balance to this subtree */
|
||||
node = this.rotate(node);
|
||||
// Return root node of subtree
|
||||
return node;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
search(val: number): TreeNode {
|
||||
let cur = this.root;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur !== null) {
|
||||
if (cur.val < val) {
|
||||
// Target node is in cur's right subtree
|
||||
cur = cur.right;
|
||||
} else if (cur.val > val) {
|
||||
// Target node is in cur's left subtree
|
||||
cur = cur.left;
|
||||
} else {
|
||||
// Found target node, exit loop
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Return target node
|
||||
return cur;
|
||||
}
|
||||
}
|
||||
|
||||
function testInsert(tree: AVLTree, val: number): void {
|
||||
tree.insert(val);
|
||||
console.log('\nInsert node ' + val + ', AVL tree is');
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
function testRemove(tree: AVLTree, val: number): void {
|
||||
tree.remove(val);
|
||||
console.log('\nRemove node ' + val + ', AVL tree is');
|
||||
printTree(tree.root);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
|
||||
const avlTree = new AVLTree();
|
||||
/* Insert node */
|
||||
// Delete nodes
|
||||
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);
|
||||
|
||||
/* Please pay attention to how the AVL tree maintains balance after deleting nodes */
|
||||
testInsert(avlTree, 7);
|
||||
|
||||
/* Remove node */
|
||||
// Delete node with degree 1
|
||||
testRemove(avlTree, 8); // Delete node with degree 2
|
||||
testRemove(avlTree, 5); // Remove node with degree 1
|
||||
testRemove(avlTree, 4); // Remove node with degree 2
|
||||
|
||||
/* Search node */
|
||||
const node = avlTree.search(7);
|
||||
console.log('\nFound node object is', node, ', node value = ' + node.val);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,146 @@
|
||||
/**
|
||||
* File: binary_search_tree.ts
|
||||
* Created Time: 2022-12-14
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { TreeNode } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Binary search tree */
|
||||
class BinarySearchTree {
|
||||
private root: TreeNode | null;
|
||||
|
||||
/* Constructor */
|
||||
constructor() {
|
||||
// Initialize empty tree
|
||||
this.root = null;
|
||||
}
|
||||
|
||||
/* Get binary tree root node */
|
||||
getRoot(): TreeNode | null {
|
||||
return this.root;
|
||||
}
|
||||
|
||||
/* Search node */
|
||||
search(num: number): TreeNode | null {
|
||||
let cur = this.root;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur !== null) {
|
||||
// Target node is in cur's right subtree
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Target node is in cur's left subtree
|
||||
else if (cur.val > num) cur = cur.left;
|
||||
// Found target node, exit loop
|
||||
else break;
|
||||
}
|
||||
// Return target node
|
||||
return cur;
|
||||
}
|
||||
|
||||
/* Insert node */
|
||||
insert(num: number): void {
|
||||
// If tree is empty, initialize root node
|
||||
if (this.root === null) {
|
||||
this.root = new TreeNode(num);
|
||||
return;
|
||||
}
|
||||
let cur: TreeNode | null = this.root,
|
||||
pre: TreeNode | null = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur !== null) {
|
||||
// Found duplicate node, return directly
|
||||
if (cur.val === num) return;
|
||||
pre = cur;
|
||||
// Insertion position is in cur's right subtree
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Insertion position is in cur's left subtree
|
||||
else cur = cur.left;
|
||||
}
|
||||
// Insert node
|
||||
const node = new TreeNode(num);
|
||||
if (pre!.val < num) pre!.right = node;
|
||||
else pre!.left = node;
|
||||
}
|
||||
|
||||
/* Remove node */
|
||||
remove(num: number): void {
|
||||
// If tree is empty, return directly
|
||||
if (this.root === null) return;
|
||||
let cur: TreeNode | null = this.root,
|
||||
pre: TreeNode | null = null;
|
||||
// Loop search, exit after passing leaf node
|
||||
while (cur !== null) {
|
||||
// Found node to delete, exit loop
|
||||
if (cur.val === num) break;
|
||||
pre = cur;
|
||||
// Node to delete is in cur's right subtree
|
||||
if (cur.val < num) cur = cur.right;
|
||||
// Node to delete is in cur's left subtree
|
||||
else cur = cur.left;
|
||||
}
|
||||
// If no node to delete, return directly
|
||||
if (cur === null) return;
|
||||
// Number of child nodes = 0 or 1
|
||||
if (cur.left === null || cur.right === null) {
|
||||
// When number of child nodes = 0 / 1, child = null / that child node
|
||||
const child: TreeNode | null =
|
||||
cur.left !== null ? cur.left : cur.right;
|
||||
// Delete node cur
|
||||
if (cur !== this.root) {
|
||||
if (pre!.left === cur) pre!.left = child;
|
||||
else pre!.right = child;
|
||||
} else {
|
||||
// If deleted node is root node, reassign root node
|
||||
this.root = child;
|
||||
}
|
||||
}
|
||||
// Number of child nodes = 2
|
||||
else {
|
||||
// Get next node of cur in inorder traversal
|
||||
let tmp: TreeNode | null = cur.right;
|
||||
while (tmp!.left !== null) {
|
||||
tmp = tmp!.left;
|
||||
}
|
||||
// Recursively delete node tmp
|
||||
this.remove(tmp!.val);
|
||||
// Replace cur with tmp
|
||||
cur.val = tmp!.val;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary search tree */
|
||||
const bst = new BinarySearchTree();
|
||||
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
|
||||
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('\nInitialized binary tree is\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Search node */
|
||||
const node = bst.search(7);
|
||||
console.log(
|
||||
'\nFound node object is ' + node + ', node value = ' + (node ? node.val : 'null')
|
||||
);
|
||||
|
||||
/* Insert node */
|
||||
bst.insert(16);
|
||||
console.log('\nAfter inserting node 16, binary tree is\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
/* Remove node */
|
||||
bst.remove(1);
|
||||
console.log('\nAfter removing node 1, binary tree is\n');
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(2);
|
||||
console.log('\nAfter removing node 2, binary tree is\n');
|
||||
printTree(bst.getRoot());
|
||||
bst.remove(4);
|
||||
console.log('\nAfter removing node 4, binary tree is\n');
|
||||
printTree(bst.getRoot());
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: binary_tree.ts
|
||||
* Created Time: 2022-12-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { TreeNode } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Initialize binary tree */
|
||||
// Initialize nodes
|
||||
let n1 = new TreeNode(1),
|
||||
n2 = new TreeNode(2),
|
||||
n3 = new TreeNode(3),
|
||||
n4 = new TreeNode(4),
|
||||
n5 = new TreeNode(5);
|
||||
// Build references (pointers) between nodes
|
||||
n1.left = n2;
|
||||
n1.right = n3;
|
||||
n2.left = n4;
|
||||
n2.right = n5;
|
||||
console.log('\nInitialize binary tree\n');
|
||||
printTree(n1);
|
||||
|
||||
/* Insert node P between n1 -> n2 */
|
||||
const P = new TreeNode(0);
|
||||
// Delete node
|
||||
n1.left = P;
|
||||
P.left = n2;
|
||||
console.log('\nAfter inserting node P\n');
|
||||
printTree(n1);
|
||||
// Remove node P
|
||||
n1.left = n2;
|
||||
console.log('\nAfter removing node P\n');
|
||||
printTree(n1);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* File: binary_tree_bfs.ts
|
||||
* Created Time: 2022-12-14
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
/* Level-order traversal */
|
||||
function levelOrder(root: TreeNode | null): number[] {
|
||||
// Initialize queue, add root node
|
||||
const queue = [root];
|
||||
// Initialize a list to save the traversal sequence
|
||||
const list: number[] = [];
|
||||
while (queue.length) {
|
||||
let node = queue.shift() as TreeNode; // Dequeue
|
||||
list.push(node.val); // Save node value
|
||||
if (node.left) {
|
||||
queue.push(node.left); // Left child node enqueue
|
||||
}
|
||||
if (node.right) {
|
||||
queue.push(node.right); // Right child node enqueue
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree\n');
|
||||
printTree(root);
|
||||
|
||||
/* Level-order traversal */
|
||||
const list = levelOrder(root);
|
||||
console.log('\nLevel-order traversal node print sequence = ' + list);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* File: binary_tree_dfs.ts
|
||||
* Created Time: 2022-12-14
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { type TreeNode } from '../modules/TreeNode';
|
||||
import { arrToTree } from '../modules/TreeNode';
|
||||
import { printTree } from '../modules/PrintUtil';
|
||||
|
||||
// Initialize list for storing traversal sequence
|
||||
const list: number[] = [];
|
||||
|
||||
/* Preorder traversal */
|
||||
function preOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: root node -> left subtree -> right subtree
|
||||
list.push(root.val);
|
||||
preOrder(root.left);
|
||||
preOrder(root.right);
|
||||
}
|
||||
|
||||
/* Inorder traversal */
|
||||
function inOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: left subtree -> root node -> right subtree
|
||||
inOrder(root.left);
|
||||
list.push(root.val);
|
||||
inOrder(root.right);
|
||||
}
|
||||
|
||||
/* Postorder traversal */
|
||||
function postOrder(root: TreeNode | null): void {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
// Visit priority: left subtree -> right subtree -> root node
|
||||
postOrder(root.left);
|
||||
postOrder(root.right);
|
||||
list.push(root.val);
|
||||
}
|
||||
|
||||
/* Driver Code */
|
||||
/* Initialize binary tree */
|
||||
// Here we use a function to generate a binary tree directly from an array
|
||||
const root = arrToTree([1, 2, 3, 4, 5, 6, 7]);
|
||||
console.log('\nInitialize binary tree\n');
|
||||
printTree(root);
|
||||
|
||||
/* Preorder traversal */
|
||||
list.length = 0;
|
||||
preOrder(root);
|
||||
console.log('\nPreorder traversal node print sequence = ' + list);
|
||||
|
||||
/* Inorder traversal */
|
||||
list.length = 0;
|
||||
inOrder(root);
|
||||
console.log('\nInorder traversal node print sequence = ' + list);
|
||||
|
||||
/* Postorder traversal */
|
||||
list.length = 0;
|
||||
postOrder(root);
|
||||
console.log('\nPostorder traversal node print sequence = ' + list);
|
||||
|
||||
export {};
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* File: ListNode.ts
|
||||
* Created Time: 2022-12-10
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Linked list node */
|
||||
class ListNode {
|
||||
val: number;
|
||||
next: ListNode | null;
|
||||
constructor(val?: number, next?: ListNode | null) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.next = next === undefined ? null : next;
|
||||
}
|
||||
}
|
||||
|
||||
/* Deserialize array to linked list */
|
||||
function arrToLinkedList(arr: number[]): ListNode | null {
|
||||
const dum: ListNode = new ListNode(0);
|
||||
let head = dum;
|
||||
for (const val of arr) {
|
||||
head.next = new ListNode(val);
|
||||
head = head.next;
|
||||
}
|
||||
return dum.next;
|
||||
}
|
||||
|
||||
export { ListNode, arrToLinkedList };
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* File: PrintUtil.ts
|
||||
* Created Time: 2022-12-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
import { ListNode } from './ListNode';
|
||||
import { TreeNode, arrToTree } from './TreeNode';
|
||||
|
||||
/* Print linked list */
|
||||
function printLinkedList(head: ListNode | null): void {
|
||||
const list: string[] = [];
|
||||
while (head !== null) {
|
||||
list.push(head.val.toString());
|
||||
head = head.next;
|
||||
}
|
||||
console.log(list.join(' -> '));
|
||||
}
|
||||
|
||||
class Trunk {
|
||||
prev: Trunk | null;
|
||||
str: string;
|
||||
|
||||
constructor(prev: Trunk | null, str: string) {
|
||||
this.prev = prev;
|
||||
this.str = str;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Print binary tree
|
||||
* This tree printer is borrowed from TECHIE DELIGHT
|
||||
* https://www.techiedelight.com/c-program-print-binary-tree/
|
||||
*/
|
||||
function printTree(root: TreeNode | null) {
|
||||
printTreeHelper(root, null, false);
|
||||
}
|
||||
|
||||
/* Print binary tree */
|
||||
function printTreeHelper(
|
||||
root: TreeNode | null,
|
||||
prev: Trunk | null,
|
||||
isRight: boolean
|
||||
) {
|
||||
if (root === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
let prev_str = ' ';
|
||||
const trunk = new Trunk(prev, prev_str);
|
||||
|
||||
printTreeHelper(root.right, trunk, true);
|
||||
|
||||
if (prev === null) {
|
||||
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 = ' |';
|
||||
|
||||
printTreeHelper(root.left, trunk, false);
|
||||
}
|
||||
|
||||
function showTrunks(p: Trunk | null) {
|
||||
if (p === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
showTrunks(p.prev);
|
||||
process.stdout.write(p.str);
|
||||
}
|
||||
|
||||
/* Print heap */
|
||||
function printHeap(arr: number[]): void {
|
||||
console.log('Heap array representation:');
|
||||
console.log(arr);
|
||||
console.log('Heap tree representation:');
|
||||
const root = arrToTree(arr);
|
||||
printTree(root);
|
||||
}
|
||||
|
||||
export { printLinkedList, printTree, printHeap };
|
||||
@@ -0,0 +1,37 @@
|
||||
/**
|
||||
* File: TreeNode.ts
|
||||
* Created Time: 2022-12-13
|
||||
* Author: Justin (xiefahit@gmail.com)
|
||||
*/
|
||||
|
||||
/* Binary tree node */
|
||||
class TreeNode {
|
||||
val: number; // Node value
|
||||
height: number; // Node height
|
||||
left: TreeNode | null; // Left child pointer
|
||||
right: TreeNode | null; // Right child pointer
|
||||
constructor(
|
||||
val?: number,
|
||||
height?: number,
|
||||
left?: TreeNode | null,
|
||||
right?: TreeNode | null
|
||||
) {
|
||||
this.val = val === undefined ? 0 : val;
|
||||
this.height = height === undefined ? 0 : height;
|
||||
this.left = left === undefined ? null : left;
|
||||
this.right = right === undefined ? null : right;
|
||||
}
|
||||
}
|
||||
|
||||
/* Deserialize array to binary tree */
|
||||
function arrToTree(arr: (number | null)[], i: number = 0): TreeNode | null {
|
||||
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;
|
||||
}
|
||||
|
||||
export { TreeNode, arrToTree };
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* File: Vertex.ts
|
||||
* Created Time: 2023-02-15
|
||||
* Author: Zhuo Qinyue (1403450829@qq.com)
|
||||
*/
|
||||
|
||||
/* Vertex class */
|
||||
class Vertex {
|
||||
val: number;
|
||||
constructor(val: number) {
|
||||
this.val = val;
|
||||
}
|
||||
|
||||
/* Input value list vals, return vertex list vets */
|
||||
public static valsToVets(vals: number[]): Vertex[] {
|
||||
const vets: Vertex[] = [];
|
||||
for (let i = 0; i < vals.length; i++) {
|
||||
vets[i] = new Vertex(vals[i]);
|
||||
}
|
||||
return vets;
|
||||
}
|
||||
|
||||
/* Input vertex list vets, return value list vals */
|
||||
public static vetsToVals(vets: Vertex[]): number[] {
|
||||
const vals: number[] = [];
|
||||
for (const vet of vets) {
|
||||
vals.push(vet.val);
|
||||
}
|
||||
return vals;
|
||||
}
|
||||
}
|
||||
|
||||
export { Vertex };
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"check": "tsc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.9.2",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"module": "esnext",
|
||||
"moduleResolution": "node",
|
||||
"types": ["@types/node"],
|
||||
"noEmit": true,
|
||||
"target": "esnext",
|
||||
},
|
||||
"include": ["chapter_*/*.ts"],
|
||||
"exclude": ["node_modules"]
|
||||
}
|
||||
Reference in New Issue
Block a user