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:
Yudong Jin
2025-12-31 07:44:52 +08:00
committed by GitHub
parent 45e1295241
commit 2778a6f9c7
1284 changed files with 71557 additions and 3275 deletions
+88
View File
@@ -0,0 +1,88 @@
# CSharp formatting rules
[*.cs]
csharp_new_line_before_open_brace = none
csharp_new_line_before_else = false
csharp_new_line_before_catch = false
csharp_new_line_before_finally = false
csharp_indent_labels = one_less_than_current
csharp_using_directive_placement = outside_namespace:silent
csharp_prefer_simple_using_statement = true:suggestion
csharp_prefer_braces = true:silent
csharp_style_namespace_declarations = block_scoped:silent
csharp_style_prefer_method_group_conversion = true:silent
csharp_style_prefer_top_level_statements = true:silent
csharp_style_prefer_primary_constructors = true:suggestion
csharp_style_expression_bodied_methods = false:silent
csharp_style_expression_bodied_constructors = false:silent
csharp_style_expression_bodied_operators = false:silent
csharp_style_expression_bodied_properties = true:silent
csharp_style_expression_bodied_indexers = true:silent
csharp_style_expression_bodied_accessors = true:silent
csharp_style_expression_bodied_lambdas = true:silent
# CS8981: The type name only contains lower-cased ascii characters. Such names may become reserved for the language.
dotnet_diagnostic.CS8981.severity = silent
# IDE1006: Naming Styles
dotnet_diagnostic.IDE1006.severity = silent
# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = silent
[*.{cs,vb}]
#### Naming styles ####
# Naming rules
dotnet_naming_rule.interface_should_be_begins_with_i.severity = suggestion
dotnet_naming_rule.interface_should_be_begins_with_i.symbols = interface
dotnet_naming_rule.interface_should_be_begins_with_i.style = begins_with_i
dotnet_naming_rule.types_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.types_should_be_pascal_case.symbols = types
dotnet_naming_rule.types_should_be_pascal_case.style = pascal_case
dotnet_naming_rule.non_field_members_should_be_pascal_case.severity = suggestion
dotnet_naming_rule.non_field_members_should_be_pascal_case.symbols = non_field_members
dotnet_naming_rule.non_field_members_should_be_pascal_case.style = pascal_case
# Symbol specifications
dotnet_naming_symbols.interface.applicable_kinds = interface
dotnet_naming_symbols.interface.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.interface.required_modifiers =
dotnet_naming_symbols.types.applicable_kinds = class, struct, interface, enum
dotnet_naming_symbols.types.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.types.required_modifiers =
dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method
dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected
dotnet_naming_symbols.non_field_members.required_modifiers =
# Naming styles
dotnet_naming_style.begins_with_i.required_prefix = I
dotnet_naming_style.begins_with_i.required_suffix =
dotnet_naming_style.begins_with_i.word_separator =
dotnet_naming_style.begins_with_i.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_naming_style.pascal_case.required_prefix =
dotnet_naming_style.pascal_case.required_suffix =
dotnet_naming_style.pascal_case.word_separator =
dotnet_naming_style.pascal_case.capitalization = pascal_case
dotnet_style_operator_placement_when_wrapping = beginning_of_line
tab_width = 4
indent_size = 4
end_of_line = crlf
# IDE0040: Add accessibility modifiers
dotnet_diagnostic.IDE0040.severity = silent
# IDE0044: Add readonly modifier
dotnet_diagnostic.IDE0044.severity = silent
+5
View File
@@ -0,0 +1,5 @@
.idea/
.vs/
obj/
.Debug
bin/
+3
View File
@@ -0,0 +1,3 @@
global using NUnit.Framework;
global using hello_algo.utils;
global using System.Text;
@@ -0,0 +1,107 @@
// File: array.cs
// Created Time: 2022-12-14
// Author: mingXta (1195669834@qq.com)
namespace hello_algo.chapter_array_and_linkedlist;
public class array {
/* Random access to element */
int RandomAccess(int[] nums) {
Random random = new();
// Randomly select a number in interval [0, nums.Length)
int randomIndex = random.Next(nums.Length);
// Retrieve and return the random element
int randomNum = nums[randomIndex];
return randomNum;
}
/* Extend array length */
int[] Extend(int[] nums, int enlarge) {
// Initialize an array with extended length
int[] res = new int[nums.Length + enlarge];
// Copy all elements from the original array to the new array
for (int 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 */
void Insert(int[] nums, int num, int index) {
// Move all elements at and after index index backward by one position
for (int 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 */
void Remove(int[] nums, int index) {
// Move all elements after index index forward by one position
for (int i = index; i < nums.Length - 1; i++) {
nums[i] = nums[i + 1];
}
}
/* Traverse array */
void Traverse(int[] nums) {
int count = 0;
// Traverse array by index
for (int i = 0; i < nums.Length; i++) {
count += nums[i];
}
// Direct traversal of array elements
foreach (int num in nums) {
count += num;
}
}
/* Find the specified element in the array */
int Find(int[] nums, int target) {
for (int i = 0; i < nums.Length; i++) {
if (nums[i] == target)
return i;
}
return -1;
}
/* Helper function, convert array to string */
string ToString(int[] nums) {
return string.Join(",", nums);
}
[Test]
public void Test() {
// Initialize array
int[] arr = new int[5];
Console.WriteLine("Array arr = " + ToString(arr));
int[] nums = [1, 3, 2, 5, 4];
Console.WriteLine("Array nums = " + ToString(nums));
// Insert element
int randomNum = RandomAccess(nums);
Console.WriteLine("Get random element in nums " + randomNum);
// Traverse array
nums = Extend(nums, 3);
Console.WriteLine("Extend array length to 8, resulting in nums = " + ToString(nums));
// Insert element
Insert(nums, 6, 3);
Console.WriteLine("Insert number 6 at index 3, resulting in nums = " + ToString(nums));
// Remove element
Remove(nums, 2);
Console.WriteLine("Remove element at index 2, resulting in nums = " + ToString(nums));
// Traverse array
Traverse(nums);
// Find element
int index = Find(nums, 3);
Console.WriteLine("Find element 3 in nums, get index = " + index);
}
}
@@ -0,0 +1,80 @@
// File: linked_list.cs
// Created Time: 2022-12-16
// Author: mingXta (1195669834@qq.com)
namespace hello_algo.chapter_array_and_linkedlist;
public class linked_list {
/* Insert node P after node n0 in the linked list */
void Insert(ListNode n0, ListNode P) {
ListNode? n1 = n0.next;
P.next = n1;
n0.next = P;
}
/* Remove the first node after node n0 in the linked list */
void Remove(ListNode n0) {
if (n0.next == null)
return;
// n0 -> P -> n1
ListNode P = n0.next;
ListNode? n1 = P.next;
n0.next = n1;
}
/* Access the node at index index in the linked list */
ListNode? Access(ListNode? head, int index) {
for (int i = 0; i < index; i++) {
if (head == null)
return null;
head = head.next;
}
return head;
}
/* Find the first node with value target in the linked list */
int Find(ListNode? head, int target) {
int index = 0;
while (head != null) {
if (head.val == target)
return index;
head = head.next;
index++;
}
return -1;
}
[Test]
public void Test() {
// Initialize linked list
// Initialize each node
ListNode n0 = new(1);
ListNode n1 = new(3);
ListNode n2 = new(2);
ListNode n3 = new(5);
ListNode n4 = new(4);
// Build references between nodes
n0.next = n1;
n1.next = n2;
n2.next = n3;
n3.next = n4;
Console.WriteLine($"Initialized linked list is{n0}");
// Insert node
Insert(n0, new ListNode(0));
Console.WriteLine($"Linked list after node insertion is{n0}");
// Remove node
Remove(n0);
Console.WriteLine($"Linked list after node deletion is{n0}");
// Access node
ListNode? node = Access(n0, 3);
Console.WriteLine($"Value of node at index 3 in linked list = {node?.val}");
// Search node
int index = Find(n0, 2);
Console.WriteLine($"Index of node with value 2 in linked list = {index}");
}
}
@@ -0,0 +1,66 @@
/**
* File: list.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_array_and_linkedlist;
public class list {
[Test]
public void Test() {
/* Initialize list */
int[] numbers = [1, 3, 2, 5, 4];
List<int> nums = [.. numbers];
Console.WriteLine("List nums = " + string.Join(",", nums));
/* Update element */
int num = nums[1];
Console.WriteLine("Access element at index 1, get num = " + num);
/* Add elements at the end */
nums[1] = 0;
Console.WriteLine("Update element at index 1 to 0, resulting in nums = " + string.Join(",", nums));
/* Remove element */
nums.Clear();
Console.WriteLine("After clearing list, nums = " + string.Join(",", nums));
/* Direct traversal of list elements */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
Console.WriteLine("After adding elements, nums = " + string.Join(",", nums));
/* Sort list */
nums.Insert(3, 6);
Console.WriteLine("Insert number 6 at index 3, resulting in nums = " + string.Join(",", nums));
/* Remove element */
nums.RemoveAt(3);
Console.WriteLine("Remove element at index 3, resulting in nums = " + string.Join(",", nums));
/* Traverse list by index */
int count = 0;
for (int i = 0; i < nums.Count; i++) {
count += nums[i];
}
/* Directly traverse list elements */
count = 0;
foreach (int x in nums) {
count += x;
}
/* Concatenate two lists */
List<int> nums1 = [6, 8, 7, 10, 9];
nums.AddRange(nums1);
Console.WriteLine("Concatenate list nums1 to nums, resulting in nums = " + string.Join(",", nums));
/* Sort list */
nums.Sort(); // After sorting, list elements are arranged from smallest to largest
Console.WriteLine("After sorting list, nums = " + string.Join(",", nums));
}
}
@@ -0,0 +1,144 @@
/**
* File: my_list.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_array_and_linkedlist;
/* List class */
class MyList {
private int[] arr; // Array (stores list elements)
private int arrCapacity = 10; // List capacity
private int arrSize = 0; // List length (current number of elements)
private readonly int extendRatio = 2; // Multiple by which the list capacity is extended each time
/* Constructor */
public MyList() {
arr = new int[arrCapacity];
}
/* Get list length (current number of elements) */
public int Size() {
return arrSize;
}
/* Get list capacity */
public int Capacity() {
return arrCapacity;
}
/* Update element */
public int Get(int index) {
// If the index is out of bounds, throw an exception, as below
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
return arr[index];
}
/* Add elements at the end */
public void Set(int index, int num) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
arr[index] = num;
}
/* Direct traversal of list elements */
public void Add(int num) {
// When the number of elements exceeds capacity, trigger the extension mechanism
if (arrSize == arrCapacity)
ExtendCapacity();
arr[arrSize] = num;
// Update the number of elements
arrSize++;
}
/* Sort list */
public void Insert(int index, int num) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
// When the number of elements exceeds capacity, trigger the extension mechanism
if (arrSize == arrCapacity)
ExtendCapacity();
// Move all elements after index index forward by one position
for (int j = arrSize - 1; j >= index; j--) {
arr[j + 1] = arr[j];
}
arr[index] = num;
// Update the number of elements
arrSize++;
}
/* Remove element */
public int Remove(int index) {
if (index < 0 || index >= arrSize)
throw new IndexOutOfRangeException("Index out of bounds");
int num = arr[index];
// Move all elements after index forward by one position
for (int j = index; j < arrSize - 1; j++) {
arr[j] = arr[j + 1];
}
// Update the number of elements
arrSize--;
// Return the removed element
return num;
}
/* Driver Code */
public void ExtendCapacity() {
// Create new array of length arrCapacity * extendRatio and copy original array to new array
Array.Resize(ref arr, arrCapacity * extendRatio);
// Add elements at the end
arrCapacity = arr.Length;
}
/* Convert list to array */
public int[] ToArray() {
// Elements enqueue
int[] arr = new int[arrSize];
for (int i = 0; i < arrSize; i++) {
arr[i] = Get(i);
}
return arr;
}
}
public class my_list {
[Test]
public void Test() {
/* Initialize list */
MyList nums = new();
/* Direct traversal of list elements */
nums.Add(1);
nums.Add(3);
nums.Add(2);
nums.Add(5);
nums.Add(4);
Console.WriteLine("List nums = " + string.Join(",", nums.ToArray()) +
", capacity = " + nums.Capacity() + ", length = " + nums.Size());
/* Sort list */
nums.Insert(3, 6);
Console.WriteLine("Insert number 6 at index 3, resulting in nums = " + string.Join(",", nums.ToArray()));
/* Remove element */
nums.Remove(3);
Console.WriteLine("Remove element at index 3, resulting in nums = " + string.Join(",", nums.ToArray()));
/* Update element */
int num = nums.Get(1);
Console.WriteLine("Access element at index 1, get num = " + num);
/* Add elements at the end */
nums.Set(1, 0);
Console.WriteLine("Update element at index 1 to 0, resulting in nums = " + string.Join(",", nums.ToArray()));
/* Test capacity expansion mechanism */
for (int i = 0; i < 10; i++) {
// At i = 5, the list length will exceed the list capacity, triggering the expansion mechanism
nums.Add(i);
}
Console.WriteLine("List nums after expansion = " + string.Join(",", nums.ToArray()) +
", capacity = " + nums.Capacity() + ", length = " + nums.Size());
}
}
@@ -0,0 +1,76 @@
/**
* File: n_queens.cs
* Created Time: 2023-05-04
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class n_queens {
/* Backtracking algorithm: N queens */
void Backtrack(int row, int n, List<List<string>> state, List<List<List<string>>> res,
bool[] cols, bool[] diags1, bool[] diags2) {
// When all rows are placed, record the solution
if (row == n) {
List<List<string>> copyState = [];
foreach (List<string> sRow in state) {
copyState.Add(new List<string>(sRow));
}
res.Add(copyState);
return;
}
// Traverse all columns
for (int col = 0; col < n; col++) {
// Calculate the main diagonal and anti-diagonal corresponding to this cell
int diag1 = row - col + n - 1;
int 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 */
List<List<List<string>>> NQueens(int n) {
// Initialize an n*n chessboard, where 'Q' represents a queen and '#' represents an empty cell
List<List<string>> state = [];
for (int i = 0; i < n; i++) {
List<string> row = [];
for (int j = 0; j < n; j++) {
row.Add("#");
}
state.Add(row);
}
bool[] cols = new bool[n]; // Record whether there is a queen in the column
bool[] diags1 = new bool[2 * n - 1]; // Record whether there is a queen on the main diagonal
bool[] diags2 = new bool[2 * n - 1]; // Record whether there is a queen on the anti-diagonal
List<List<List<string>>> res = [];
Backtrack(0, n, state, res, cols, diags1, diags2);
return res;
}
[Test]
public void Test() {
int n = 4;
List<List<List<string>>> res = NQueens(n);
Console.WriteLine("Input board size is " + n);
Console.WriteLine("Total queen placement solutions: " + res.Count + " solutions");
foreach (List<List<string>> state in res) {
Console.WriteLine("--------------------");
foreach (List<string> row in state) {
PrintUtil.PrintList(row);
}
}
}
}
@@ -0,0 +1,53 @@
/**
* File: permutations_i.cs
* Created Time: 2023-04-24
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class permutations_i {
/* Backtracking algorithm: Permutations I */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
// When the state length equals the number of elements, record the solution
if (state.Count == choices.Length) {
res.Add(new List<int>(state));
return;
}
// Traverse all choices
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// Pruning: do not allow repeated selection of elements
if (!selected[i]) {
// Attempt: make choice, update state
selected[i] = true;
state.Add(choice);
// Proceed to the next round of selection
Backtrack(state, choices, selected, res);
// Backtrack: undo choice, restore to previous state
selected[i] = false;
state.RemoveAt(state.Count - 1);
}
}
}
/* Permutations I */
List<List<int>> PermutationsI(int[] nums) {
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
[Test]
public void Test() {
int[] nums = [1, 2, 3];
List<List<int>> res = PermutationsI(nums);
Console.WriteLine("Input array nums = " + string.Join(", ", nums));
Console.WriteLine("All permutations res = ");
foreach (List<int> permutation in res) {
PrintUtil.PrintList(permutation);
}
}
}
@@ -0,0 +1,55 @@
/**
* File: permutations_ii.cs
* Created Time: 2023-04-24
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class permutations_ii {
/* Backtracking algorithm: Permutations II */
void Backtrack(List<int> state, int[] choices, bool[] selected, List<List<int>> res) {
// When the state length equals the number of elements, record the solution
if (state.Count == choices.Length) {
res.Add(new List<int>(state));
return;
}
// Traverse all choices
HashSet<int> duplicated = [];
for (int i = 0; i < choices.Length; i++) {
int choice = choices[i];
// Pruning: do not allow repeated selection of elements and do not allow repeated selection of equal elements
if (!selected[i] && !duplicated.Contains(choice)) {
// Attempt: make choice, update state
duplicated.Add(choice); // Record the selected element value
selected[i] = true;
state.Add(choice);
// Proceed to the next round of selection
Backtrack(state, choices, selected, res);
// Backtrack: undo choice, restore to previous state
selected[i] = false;
state.RemoveAt(state.Count - 1);
}
}
}
/* Permutations II */
List<List<int>> PermutationsII(int[] nums) {
List<List<int>> res = [];
Backtrack([], nums, new bool[nums.Length], res);
return res;
}
[Test]
public void Test() {
int[] nums = [1, 2, 2];
List<List<int>> res = PermutationsII(nums);
Console.WriteLine("Input array nums = " + string.Join(", ", nums));
Console.WriteLine("All permutations res = ");
foreach (List<int> permutation in res) {
PrintUtil.PrintList(permutation);
}
}
}
@@ -0,0 +1,37 @@
/**
* File: preorder_traversal_i_compact.cs
* Created Time: 2023-04-17
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class preorder_traversal_i_compact {
List<TreeNode> res = [];
/* Preorder traversal: Example 1 */
void PreOrder(TreeNode? root) {
if (root == null) {
return;
}
if (root.val == 7) {
// Record solution
res.Add(root);
}
PreOrder(root.left);
PreOrder(root.right);
}
[Test]
public void Test() {
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree");
PrintUtil.PrintTree(root);
// Preorder traversal
PreOrder(root);
Console.WriteLine("\nOutput all nodes with value 7");
PrintUtil.PrintList(res.Select(p => p.val).ToList());
}
}
@@ -0,0 +1,44 @@
/**
* File: preorder_traversal_ii_compact.cs
* Created Time: 2023-04-17
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class preorder_traversal_ii_compact {
List<TreeNode> path = [];
List<List<TreeNode>> res = [];
/* Preorder traversal: Example 2 */
void PreOrder(TreeNode? root) {
if (root == null) {
return;
}
// Attempt
path.Add(root);
if (root.val == 7) {
// Record solution
res.Add(new List<TreeNode>(path));
}
PreOrder(root.left);
PreOrder(root.right);
// Backtrack
path.RemoveAt(path.Count - 1);
}
[Test]
public void Test() {
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree");
PrintUtil.PrintTree(root);
// Preorder traversal
PreOrder(root);
Console.WriteLine("\nOutput all paths from root node to node 7");
foreach (List<TreeNode> path in res) {
PrintUtil.PrintList(path.Select(p => p.val).ToList());
}
}
}
@@ -0,0 +1,45 @@
/**
* File: preorder_traversal_iii_compact.cs
* Created Time: 2023-04-17
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class preorder_traversal_iii_compact {
List<TreeNode> path = [];
List<List<TreeNode>> res = [];
/* Preorder traversal: Example 3 */
void PreOrder(TreeNode? root) {
// Pruning
if (root == null || root.val == 3) {
return;
}
// Attempt
path.Add(root);
if (root.val == 7) {
// Record solution
res.Add(new List<TreeNode>(path));
}
PreOrder(root.left);
PreOrder(root.right);
// Backtrack
path.RemoveAt(path.Count - 1);
}
[Test]
public void Test() {
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree");
PrintUtil.PrintTree(root);
// Preorder traversal
PreOrder(root);
Console.WriteLine("\nOutput all paths from root node to node 7, paths do not include nodes with value 3");
foreach (List<TreeNode> path in res) {
PrintUtil.PrintList(path.Select(p => p.val).ToList());
}
}
}
@@ -0,0 +1,72 @@
/**
* File: preorder_traversal_iii_template.cs
* Created Time: 2023-04-17
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class preorder_traversal_iii_template {
/* Check if the current state is a solution */
bool IsSolution(List<TreeNode> state) {
return state.Count != 0 && state[^1].val == 7;
}
/* Record solution */
void RecordSolution(List<TreeNode> state, List<List<TreeNode>> res) {
res.Add(new List<TreeNode>(state));
}
/* Check if the choice is valid under the current state */
bool IsValid(List<TreeNode> state, TreeNode choice) {
return choice != null && choice.val != 3;
}
/* Update state */
void MakeChoice(List<TreeNode> state, TreeNode choice) {
state.Add(choice);
}
/* Restore state */
void UndoChoice(List<TreeNode> state, TreeNode choice) {
state.RemoveAt(state.Count - 1);
}
/* Backtracking algorithm: Example 3 */
void Backtrack(List<TreeNode> state, List<TreeNode> choices, List<List<TreeNode>> res) {
// Check if it is a solution
if (IsSolution(state)) {
// Record solution
RecordSolution(state, res);
}
// Traverse all choices
foreach (TreeNode choice in 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, choice);
}
}
}
[Test]
public void Test() {
TreeNode? root = TreeNode.ListToTree([1, 7, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree");
PrintUtil.PrintTree(root);
// Backtracking algorithm
List<List<TreeNode>> res = [];
List<TreeNode> choices = [root!];
Backtrack([], choices, res);
Console.WriteLine("\nOutput all paths from root node to node 7, requiring paths do not include nodes with value 3");
foreach (List<TreeNode> path in res) {
PrintUtil.PrintList(path.Select(p => p.val).ToList());
}
}
}
@@ -0,0 +1,55 @@
/**
* File: subset_sum_i.cs
* Created Time: 2023-06-25
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class subset_sum_i {
/* Backtracking algorithm: Subset sum I */
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
// When the subset sum equals target, record the solution
if (target == 0) {
res.Add(new List<int>(state));
return;
}
// Traverse all choices
// Pruning 2: start traversing from start to avoid generating duplicate subsets
for (int 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.Add(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.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum I */
List<List<int>> SubsetSumI(int[] nums, int target) {
List<int> state = []; // State (subset)
Array.Sort(nums); // Sort nums
int start = 0; // Start point for traversal
List<List<int>> res = []; // Result list (subset list)
Backtrack(state, target, nums, start, res);
return res;
}
[Test]
public void Test() {
int[] nums = [3, 4, 5];
int target = 9;
List<List<int>> res = SubsetSumI(nums, target);
Console.WriteLine("Input array nums = " + string.Join(", ", nums) + ", target = " + target);
Console.WriteLine("All subsets with sum equal to " + target + " are res = ");
foreach (var subset in res) {
PrintUtil.PrintList(subset);
}
}
}
@@ -0,0 +1,53 @@
/**
* File: subset_sum_i_naive.cs
* Created Time: 2023-06-25
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class subset_sum_i_naive {
/* Backtracking algorithm: Subset sum I */
void Backtrack(List<int> state, int target, int total, int[] choices, List<List<int>> res) {
// When the subset sum equals target, record the solution
if (total == target) {
res.Add(new List<int>(state));
return;
}
// Traverse all choices
for (int 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.Add(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.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum I (including duplicate subsets) */
List<List<int>> SubsetSumINaive(int[] nums, int target) {
List<int> state = []; // State (subset)
int total = 0; // Subset sum
List<List<int>> res = []; // Result list (subset list)
Backtrack(state, target, total, nums, res);
return res;
}
[Test]
public void Test() {
int[] nums = [3, 4, 5];
int target = 9;
List<List<int>> res = SubsetSumINaive(nums, target);
Console.WriteLine("Input array nums = " + string.Join(", ", nums) + ", target = " + target);
Console.WriteLine("All subsets with sum equal to " + target + " are res = ");
foreach (var subset in res) {
PrintUtil.PrintList(subset);
}
Console.WriteLine("Please note that this method outputs results containing duplicate sets");
}
}
@@ -0,0 +1,60 @@
/**
* File: subset_sum_ii.cs
* Created Time: 2023-06-25
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_backtracking;
public class subset_sum_ii {
/* Backtracking algorithm: Subset sum II */
void Backtrack(List<int> state, int target, int[] choices, int start, List<List<int>> res) {
// When the subset sum equals target, record the solution
if (target == 0) {
res.Add(new List<int>(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 (int 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.Add(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.RemoveAt(state.Count - 1);
}
}
/* Solve subset sum II */
List<List<int>> SubsetSumII(int[] nums, int target) {
List<int> state = []; // State (subset)
Array.Sort(nums); // Sort nums
int start = 0; // Start point for traversal
List<List<int>> res = []; // Result list (subset list)
Backtrack(state, target, nums, start, res);
return res;
}
[Test]
public void Test() {
int[] nums = [4, 4, 5];
int target = 9;
List<List<int>> res = SubsetSumII(nums, target);
Console.WriteLine("Input array nums = " + string.Join(", ", nums) + ", target = " + target);
Console.WriteLine("All subsets with sum equal to " + target + " are res = ");
foreach (var subset in res) {
PrintUtil.PrintList(subset);
}
}
}
@@ -0,0 +1,77 @@
/**
* File: iteration.cs
* Created Time: 2023-08-28
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_computational_complexity;
public class iteration {
/* for loop */
int ForLoop(int n) {
int res = 0;
// Sum 1, 2, ..., n-1, n
for (int i = 1; i <= n; i++) {
res += i;
}
return res;
}
/* while loop */
int WhileLoop(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Sum 1, 2, ..., n-1, n
while (i <= n) {
res += i;
i += 1; // Update condition variable
}
return res;
}
/* while loop (two updates) */
int WhileLoopII(int n) {
int res = 0;
int i = 1; // Initialize condition variable
// Sum 1, 4, 10, ...
while (i <= n) {
res += i;
// Update condition variable
i += 1;
i *= 2;
}
return res;
}
/* Nested for loop */
string NestedForLoop(int n) {
StringBuilder res = new();
// Loop i = 1, 2, ..., n-1, n
for (int i = 1; i <= n; i++) {
// Loop j = 1, 2, ..., n-1, n
for (int j = 1; j <= n; j++) {
res.Append($"({i}, {j}), ");
}
}
return res.ToString();
}
/* Driver Code */
[Test]
public void Test() {
int n = 5;
int res;
res = ForLoop(n);
Console.WriteLine("\nfor loop sum result res = " + res);
res = WhileLoop(n);
Console.WriteLine("\nwhile loop sum result res = " + res);
res = WhileLoopII(n);
Console.WriteLine("\nwhile loop (two updates) sum result res = " + res);
string resStr = NestedForLoop(n);
Console.WriteLine("\nDouble for loop traversal result " + resStr);
}
}
@@ -0,0 +1,78 @@
/**
* File: recursion.cs
* Created Time: 2023-08-28
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_computational_complexity;
public class recursion {
/* Recursion */
int Recur(int n) {
// Termination condition
if (n == 1)
return 1;
// Recurse: recursive call
int res = Recur(n - 1);
// Return: return result
return n + res;
}
/* Simulate recursion using iteration */
int ForLoopRecur(int n) {
// Use an explicit stack to simulate the system call stack
Stack<int> stack = new();
int res = 0;
// Recurse: recursive call
for (int i = n; i > 0; i--) {
// Simulate "recurse" with "push"
stack.Push(i);
}
// Return: return result
while (stack.Count > 0) {
// Simulate "return" with "pop"
res += stack.Pop();
}
// res = 1+2+3+...+n
return res;
}
/* Tail recursion */
int TailRecur(int n, int res) {
// Termination condition
if (n == 0)
return res;
// Tail recursive call
return TailRecur(n - 1, res + n);
}
/* Fibonacci sequence: recursion */
int Fib(int n) {
// 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)
int res = Fib(n - 1) + Fib(n - 2);
// Return result f(n)
return res;
}
/* Driver Code */
[Test]
public void Test() {
int n = 5;
int res;
res = Recur(n);
Console.WriteLine("\nRecursive function sum result res = " + res);
res = ForLoopRecur(n);
Console.WriteLine("\nUsing iteration to simulate recursive sum result res = " + res);
res = TailRecur(n, 0);
Console.WriteLine("\nTail recursive function sum result res = " + res);
res = Fib(n);
Console.WriteLine("\nThe " + n + "th term of the Fibonacci sequence is " + res);
}
}
@@ -0,0 +1,104 @@
/**
* File: space_complexity.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_computational_complexity;
public class space_complexity {
/* Function */
int Function() {
// Perform some operations
return 0;
}
/* Constant order */
void Constant(int n) {
// Constants, variables, objects occupy O(1) space
int a = 0;
int b = 0;
int[] nums = new int[10000];
ListNode node = new(0);
// Variables in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
int c = 0;
}
// Functions in the loop occupy O(1) space
for (int i = 0; i < n; i++) {
Function();
}
}
/* Linear order */
void Linear(int n) {
// Array of length n uses O(n) space
int[] nums = new int[n];
// A list of length n occupies O(n) space
List<ListNode> nodes = [];
for (int i = 0; i < n; i++) {
nodes.Add(new ListNode(i));
}
// A hash table of length n occupies O(n) space
Dictionary<int, string> map = [];
for (int i = 0; i < n; i++) {
map.Add(i, i.ToString());
}
}
/* Linear order (recursive implementation) */
void LinearRecur(int n) {
Console.WriteLine("Recursion n = " + n);
if (n == 1) return;
LinearRecur(n - 1);
}
/* Exponential order */
void Quadratic(int n) {
// Matrix uses O(n^2) space
int[,] numMatrix = new int[n, n];
// 2D list uses O(n^2) space
List<List<int>> numList = [];
for (int i = 0; i < n; i++) {
List<int> tmp = [];
for (int j = 0; j < n; j++) {
tmp.Add(0);
}
numList.Add(tmp);
}
}
/* Quadratic order (recursive implementation) */
int QuadraticRecur(int n) {
if (n <= 0) return 0;
int[] nums = new int[n];
Console.WriteLine("Recursion n = " + n + ", nums length = " + nums.Length);
return QuadraticRecur(n - 1);
}
/* Driver Code */
TreeNode? BuildTree(int n) {
if (n == 0) return null;
TreeNode root = new(0) {
left = BuildTree(n - 1),
right = BuildTree(n - 1)
};
return root;
}
[Test]
public void Test() {
int n = 5;
// Constant order
Constant(n);
// Linear order
Linear(n);
LinearRecur(n);
// Exponential order
Quadratic(n);
QuadraticRecur(n);
// Exponential order
TreeNode? root = BuildTree(n);
PrintUtil.PrintTree(root);
}
}
@@ -0,0 +1,195 @@
/**
* File: time_complexity.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_computational_complexity;
public class time_complexity {
void Algorithm(int n) {
int a = 1; // +0 (technique 1)
a += n; // +0 (technique 1)
// +n (technique 2)
for (int i = 0; i < 5 * n + 1; i++) {
Console.WriteLine(0);
}
// +n*n (technique 3)
for (int i = 0; i < 2 * n; i++) {
for (int j = 0; j < n + 1; j++) {
Console.WriteLine(0);
}
}
}
// Algorithm A time complexity: constant
void AlgorithmA(int n) {
Console.WriteLine(0);
}
// Algorithm B time complexity: linear
void AlgorithmB(int n) {
for (int i = 0; i < n; i++) {
Console.WriteLine(0);
}
}
// Algorithm C time complexity: constant
void AlgorithmC(int n) {
for (int i = 0; i < 1000000; i++) {
Console.WriteLine(0);
}
}
/* Constant order */
int Constant(int n) {
int count = 0;
int size = 100000;
for (int i = 0; i < size; i++)
count++;
return count;
}
/* Linear order */
int Linear(int n) {
int count = 0;
for (int i = 0; i < n; i++)
count++;
return count;
}
/* Linear order (traversing array) */
int ArrayTraversal(int[] nums) {
int count = 0;
// Number of iterations is proportional to the array length
foreach (int num in nums) {
count++;
}
return count;
}
/* Exponential order */
int Quadratic(int n) {
int count = 0;
// Number of iterations is quadratically related to the data size n
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
count++;
}
}
return count;
}
/* Quadratic order (bubble sort) */
int BubbleSort(int[] nums) {
int count = 0; // Counter
// Outer loop: unsorted range is [0, i]
for (int 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 (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
count += 3; // Element swap includes 3 unit operations
}
}
}
return count;
}
/* Exponential order (loop implementation) */
int Exponential(int n) {
int count = 0, bas = 1;
// Cells divide into two every round, forming sequence 1, 2, 4, 8, ..., 2^(n-1)
for (int i = 0; i < n; i++) {
for (int j = 0; j < bas; j++) {
count++;
}
bas *= 2;
}
// count = 1 + 2 + 4 + 8 + .. + 2^(n-1) = 2^n - 1
return count;
}
/* Exponential order (recursive implementation) */
int ExpRecur(int n) {
if (n == 1) return 1;
return ExpRecur(n - 1) + ExpRecur(n - 1) + 1;
}
/* Logarithmic order (loop implementation) */
int Logarithmic(int n) {
int count = 0;
while (n > 1) {
n /= 2;
count++;
}
return count;
}
/* Logarithmic order (recursive implementation) */
int LogRecur(int n) {
if (n <= 1) return 0;
return LogRecur(n / 2) + 1;
}
/* Linearithmic order */
int LinearLogRecur(int n) {
if (n <= 1) return 1;
int count = LinearLogRecur(n / 2) + LinearLogRecur(n / 2);
for (int i = 0; i < n; i++) {
count++;
}
return count;
}
/* Factorial order (recursive implementation) */
int FactorialRecur(int n) {
if (n == 0) return 1;
int count = 0;
// Split from 1 into n
for (int i = 0; i < n; i++) {
count += FactorialRecur(n - 1);
}
return count;
}
[Test]
public void Test() {
// You can modify n to run and observe the trend of the number of operations for various complexities
int n = 8;
Console.WriteLine("Input data size n = " + n);
int count = Constant(n);
Console.WriteLine("Constant order operation count = " + count);
count = Linear(n);
Console.WriteLine("Linear order operation count = " + count);
count = ArrayTraversal(new int[n]);
Console.WriteLine("Linear order (array traversal) operation count = " + count);
count = Quadratic(n);
Console.WriteLine("Quadratic order operation count = " + count);
int[] nums = new int[n];
for (int i = 0; i < n; i++)
nums[i] = n - i; // [n,n-1,...,2,1]
count = BubbleSort(nums);
Console.WriteLine("Quadratic order (bubble sort) operation count = " + count);
count = Exponential(n);
Console.WriteLine("Exponential order (loop implementation) operation count = " + count);
count = ExpRecur(n);
Console.WriteLine("Exponential order (recursive implementation) operation count = " + count);
count = Logarithmic(n);
Console.WriteLine("Logarithmic order (loop implementation) operation count = " + count);
count = LogRecur(n);
Console.WriteLine("Logarithmic order (recursive implementation) operation count = " + count);
count = LinearLogRecur(n);
Console.WriteLine("Linearithmic order (recursive implementation) operation count = " + count);
count = FactorialRecur(n);
Console.WriteLine("Factorial order (recursive implementation) operation count = " + count);
}
}
@@ -0,0 +1,49 @@
/**
* File: worst_best_time_complexity.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_computational_complexity;
public class worst_best_time_complexity {
/* Generate an array with elements { 1, 2, ..., n }, order shuffled */
int[] RandomNumbers(int n) {
int[] nums = new int[n];
// Generate array nums = { 1, 2, 3, ..., n }
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
// Randomly shuffle array elements
for (int i = 0; i < nums.Length; i++) {
int index = new Random().Next(i, nums.Length);
(nums[i], nums[index]) = (nums[index], nums[i]);
}
return nums;
}
/* Find the index of number 1 in array nums */
int FindOne(int[] nums) {
for (int 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 */
[Test]
public void Test() {
for (int i = 0; i < 10; i++) {
int n = 100;
int[] nums = RandomNumbers(n);
int index = FindOne(nums);
Console.WriteLine("\nArray [ 1, 2, ..., n ] after shuffling = " + string.Join(",", nums));
Console.WriteLine("Index of number 1 is " + index);
}
}
}
@@ -0,0 +1,46 @@
/**
* File: binary_search_recur.cs
* Created Time: 2023-07-18
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_divide_and_conquer;
public class binary_search_recur {
/* Binary search: problem f(i, j) */
int DFS(int[] nums, int target, int i, int j) {
// If the interval is empty, it means there is no target element, return -1
if (i > j) {
return -1;
}
// Calculate the midpoint index m
int m = (i + j) / 2;
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 */
int BinarySearch(int[] nums, int target) {
int n = nums.Length;
// Solve the problem f(0, n-1)
return DFS(nums, target, 0, n - 1);
}
[Test]
public void Test() {
int target = 6;
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
// Binary search (closed interval on both sides)
int index = BinarySearch(nums, target);
Console.WriteLine("Index of target element 6 = " + index);
}
}
@@ -0,0 +1,49 @@
/**
* File: build_tree.cs
* Created Time: 2023-07-18
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_divide_and_conquer;
public class build_tree {
/* Build binary tree: divide and conquer */
TreeNode? DFS(int[] preorder, Dictionary<int, int> inorderMap, int i, int l, int r) {
// Terminate when the subtree interval is empty
if (r - l < 0)
return null;
// Initialize the root node
TreeNode root = new(preorder[i]);
// Query m to divide the left and right subtrees
int m = inorderMap[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 */
TreeNode? BuildTree(int[] preorder, int[] inorder) {
// Initialize hash map, storing the mapping from inorder elements to indices
Dictionary<int, int> inorderMap = [];
for (int i = 0; i < inorder.Length; i++) {
inorderMap.TryAdd(inorder[i], i);
}
TreeNode? root = DFS(preorder, inorderMap, 0, 0, inorder.Length - 1);
return root;
}
[Test]
public void Test() {
int[] preorder = [3, 9, 2, 1, 7];
int[] inorder = [9, 3, 1, 2, 7];
Console.WriteLine("Preorder traversal = " + string.Join(", ", preorder));
Console.WriteLine("Inorder traversal = " + string.Join(", ", inorder));
TreeNode? root = BuildTree(preorder, inorder);
Console.WriteLine("The constructed binary tree is:");
PrintUtil.PrintTree(root);
}
}
@@ -0,0 +1,59 @@
/**
* File: hanota.cs
* Created Time: 2023-07-18
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_divide_and_conquer;
public class hanota {
/* Move a disk */
void Move(List<int> src, List<int> tar) {
// Take out a disk from the top of src
int pan = src[^1];
src.RemoveAt(src.Count - 1);
// Place the disk on top of tar
tar.Add(pan);
}
/* Solve the Tower of Hanoi problem f(i) */
void DFS(int i, List<int> src, List<int> buf, List<int> tar) {
// 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 */
void SolveHanota(List<int> A, List<int> B, List<int> C) {
int n = A.Count;
// Move the top n disks from A to C using B
DFS(n, A, B, C);
}
[Test]
public void Test() {
// The tail of the list is the top of the rod
List<int> A = [5, 4, 3, 2, 1];
List<int> B = [];
List<int> C = [];
Console.WriteLine("In initial state:");
Console.WriteLine("A = " + string.Join(", ", A));
Console.WriteLine("B = " + string.Join(", ", B));
Console.WriteLine("C = " + string.Join(", ", C));
SolveHanota(A, B, C);
Console.WriteLine("After disk movement is complete:");
Console.WriteLine("A = " + string.Join(", ", A));
Console.WriteLine("B = " + string.Join(", ", B));
Console.WriteLine("C = " + string.Join(", ", C));
}
}
@@ -0,0 +1,41 @@
/**
* File: climbing_stairs_backtrack.cs
* Created Time: 2023-06-30
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_backtrack {
/* Backtracking */
void Backtrack(List<int> choices, int state, int n, List<int> res) {
// When climbing to the n-th stair, add 1 to the solution count
if (state == n)
res[0]++;
// Traverse all choices
foreach (int choice in 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 */
int ClimbingStairsBacktrack(int n) {
List<int> choices = [1, 2]; // Can choose to climb up 1 or 2 stairs
int state = 0; // Start climbing from the 0-th stair
List<int> res = [0]; // Use res[0] to record the solution count
Backtrack(choices, state, n, res);
return res[0];
}
[Test]
public void Test() {
int n = 9;
int res = ClimbingStairsBacktrack(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
}
}
@@ -0,0 +1,36 @@
/**
* File: climbing_stairs_constraint_dp.cs
* Created Time: 2023-07-03
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_constraint_dp {
/* Climbing stairs with constraint: Dynamic programming */
int ClimbingStairsConstraintDP(int n) {
if (n == 1 || n == 2) {
return 1;
}
// Initialize dp table, used to store solutions to subproblems
int[,] dp = new int[n + 1, 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 (int 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];
}
[Test]
public void Test() {
int n = 9;
int res = ClimbingStairsConstraintDP(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
}
}
@@ -0,0 +1,31 @@
/**
* File: climbing_stairs_dfs.cs
* Created Time: 2023-06-30
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_dfs {
/* Search */
int DFS(int i) {
// Known dp[1] and dp[2], return them
if (i == 1 || i == 2)
return i;
// dp[i] = dp[i-1] + dp[i-2]
int count = DFS(i - 1) + DFS(i - 2);
return count;
}
/* Climbing stairs: Search */
int ClimbingStairsDFS(int n) {
return DFS(n);
}
[Test]
public void Test() {
int n = 9;
int res = ClimbingStairsDFS(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
}
}
@@ -0,0 +1,39 @@
/**
* File: climbing_stairs_dfs_mem.cs
* Created Time: 2023-06-30
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_dfs_mem {
/* Memoization search */
int DFS(int i, int[] mem) {
// 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]
int count = DFS(i - 1, mem) + DFS(i - 2, mem);
// Record dp[i]
mem[i] = count;
return count;
}
/* Climbing stairs: Memoization search */
int ClimbingStairsDFSMem(int n) {
// mem[i] records the total number of solutions to climb to the i-th stair, -1 means no record
int[] mem = new int[n + 1];
Array.Fill(mem, -1);
return DFS(n, mem);
}
[Test]
public void Test() {
int n = 9;
int res = ClimbingStairsDFSMem(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
}
}
@@ -0,0 +1,49 @@
/**
* File: climbing_stairs_dp.cs
* Created Time: 2023-06-30
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class climbing_stairs_dp {
/* Climbing stairs: Dynamic programming */
int ClimbingStairsDP(int n) {
if (n == 1 || n == 2)
return n;
// Initialize dp table, used to store solutions to subproblems
int[] dp = new int[n + 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 (int i = 3; i <= n; i++) {
dp[i] = dp[i - 1] + dp[i - 2];
}
return dp[n];
}
/* Climbing stairs: Space-optimized dynamic programming */
int ClimbingStairsDPComp(int n) {
if (n == 1 || n == 2)
return n;
int a = 1, b = 2;
for (int i = 3; i <= n; i++) {
int tmp = b;
b = a + b;
a = tmp;
}
return b;
}
[Test]
public void Test() {
int n = 9;
int res = ClimbingStairsDP(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
res = ClimbingStairsDPComp(n);
Console.WriteLine($"Climbing {n} stairs has {res} solutions");
}
}
@@ -0,0 +1,71 @@
/**
* File: coin_change.cs
* Created Time: 2023-07-12
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class coin_change {
/* Coin change: Dynamic programming */
int CoinChangeDP(int[] coins, int amt) {
int n = coins.Length;
int MAX = amt + 1;
// Initialize dp table
int[,] dp = new int[n + 1, amt + 1];
// State transition: first row and first column
for (int a = 1; a <= amt; a++) {
dp[0, a] = MAX;
}
// State transition: rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int 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 */
int CoinChangeDPComp(int[] coins, int amt) {
int n = coins.Length;
int MAX = amt + 1;
// Initialize dp table
int[] dp = new int[amt + 1];
Array.Fill(dp, MAX);
dp[0] = 0;
// State transition
for (int i = 1; i <= n; i++) {
for (int 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;
}
[Test]
public void Test() {
int[] coins = [1, 2, 5];
int amt = 4;
// Dynamic programming
int res = CoinChangeDP(coins, amt);
Console.WriteLine("Minimum number of coins needed to make target amount is " + res);
// Space-optimized dynamic programming
res = CoinChangeDPComp(coins, amt);
Console.WriteLine("Minimum number of coins needed to make target amount is " + res);
}
}
@@ -0,0 +1,68 @@
/**
* File: coin_change_ii.cs
* Created Time: 2023-07-12
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class coin_change_ii {
/* Coin change II: Dynamic programming */
int CoinChangeIIDP(int[] coins, int amt) {
int n = coins.Length;
// Initialize dp table
int[,] dp = new int[n + 1, amt + 1];
// Initialize first column
for (int i = 0; i <= n; i++) {
dp[i, 0] = 1;
}
// State transition
for (int i = 1; i <= n; i++) {
for (int 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 */
int CoinChangeIIDPComp(int[] coins, int amt) {
int n = coins.Length;
// Initialize dp table
int[] dp = new int[amt + 1];
dp[0] = 1;
// State transition
for (int i = 1; i <= n; i++) {
for (int 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];
}
[Test]
public void Test() {
int[] coins = [1, 2, 5];
int amt = 5;
// Dynamic programming
int res = CoinChangeIIDP(coins, amt);
Console.WriteLine("Number of coin combinations to make target amount is " + res);
// Space-optimized dynamic programming
res = CoinChangeIIDPComp(coins, amt);
Console.WriteLine("Number of coin combinations to make target amount is " + res);
}
}
@@ -0,0 +1,141 @@
/**
* File: edit_distance.cs
* Created Time: 2023-07-14
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class edit_distance {
/* Edit distance: Brute-force search */
int EditDistanceDFS(string s, string t, int i, int j) {
// 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[i - 1] == t[j - 1])
return EditDistanceDFS(s, t, i - 1, j - 1);
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
int insert = EditDistanceDFS(s, t, i, j - 1);
int delete = EditDistanceDFS(s, t, i - 1, j);
int replace = EditDistanceDFS(s, t, i - 1, j - 1);
// Return minimum edit steps
return Math.Min(Math.Min(insert, delete), replace) + 1;
}
/* Edit distance: Memoization search */
int EditDistanceDFSMem(string s, string t, int[][] mem, int i, int j) {
// 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[i - 1] == t[j - 1])
return EditDistanceDFSMem(s, t, mem, i - 1, j - 1);
// Minimum edit steps = minimum edit steps of insert, delete, replace + 1
int insert = EditDistanceDFSMem(s, t, mem, i, j - 1);
int delete = EditDistanceDFSMem(s, t, mem, i - 1, j);
int replace = EditDistanceDFSMem(s, t, mem, i - 1, j - 1);
// Record and return minimum edit steps
mem[i][j] = Math.Min(Math.Min(insert, delete), replace) + 1;
return mem[i][j];
}
/* Edit distance: Dynamic programming */
int EditDistanceDP(string s, string t) {
int n = s.Length, m = t.Length;
int[,] dp = new int[n + 1, m + 1];
// State transition: first row and first column
for (int i = 1; i <= n; i++) {
dp[i, 0] = i;
}
for (int j = 1; j <= m; j++) {
dp[0, j] = j;
}
// State transition: rest of the rows and columns
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (s[i - 1] == t[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(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 */
int EditDistanceDPComp(string s, string t) {
int n = s.Length, m = t.Length;
int[] dp = new int[m + 1];
// State transition: first row
for (int j = 1; j <= m; j++) {
dp[j] = j;
}
// State transition: rest of the rows
for (int i = 1; i <= n; i++) {
// State transition: first column
int leftup = dp[0]; // Temporarily store dp[i-1, j-1]
dp[0] = i;
// State transition: rest of the columns
for (int j = 1; j <= m; j++) {
int temp = dp[j];
if (s[i - 1] == t[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(Math.Min(dp[j - 1], dp[j]), leftup) + 1;
}
leftup = temp; // Update for next round's dp[i-1, j-1]
}
}
return dp[m];
}
[Test]
public void Test() {
string s = "bag";
string t = "pack";
int n = s.Length, m = t.Length;
// Brute-force search
int res = EditDistanceDFS(s, t, n, m);
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
// Memoization search
int[][] mem = new int[n + 1][];
for (int i = 0; i <= n; i++) {
mem[i] = new int[m + 1];
Array.Fill(mem[i], -1);
}
res = EditDistanceDFSMem(s, t, mem, n, m);
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
// Dynamic programming
res = EditDistanceDP(s, t);
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
// Space-optimized dynamic programming
res = EditDistanceDPComp(s, t);
Console.WriteLine("Change " + s + " to " + t + " requires a minimum of " + res + " edits");
}
}
@@ -0,0 +1,118 @@
/**
* File: knapsack.cs
* Created Time: 2023-07-07
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class knapsack {
/* 0-1 knapsack: Brute-force search */
int KnapsackDFS(int[] weight, int[] val, int i, int c) {
// 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 (weight[i - 1] > c) {
return KnapsackDFS(weight, val, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
int no = KnapsackDFS(weight, val, i - 1, c);
int yes = KnapsackDFS(weight, val, i - 1, c - weight[i - 1]) + val[i - 1];
// Return the larger value of the two options
return Math.Max(no, yes);
}
/* 0-1 knapsack: Memoization search */
int KnapsackDFSMem(int[] weight, int[] val, int[][] mem, int i, int c) {
// 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 (weight[i - 1] > c) {
return KnapsackDFSMem(weight, val, mem, i - 1, c);
}
// Calculate the maximum value of not putting in and putting in item i
int no = KnapsackDFSMem(weight, val, mem, i - 1, c);
int yes = KnapsackDFSMem(weight, val, mem, i - 1, c - weight[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 */
int KnapsackDP(int[] weight, int[] val, int cap) {
int n = weight.Length;
// Initialize dp table
int[,] dp = new int[n + 1, cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int c = 1; c <= cap; c++) {
if (weight[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 - weight[i - 1]] + val[i - 1], dp[i - 1, c]);
}
}
}
return dp[n, cap];
}
/* 0-1 knapsack: Space-optimized dynamic programming */
int KnapsackDPComp(int[] weight, int[] val, int cap) {
int n = weight.Length;
// Initialize dp table
int[] dp = new int[cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
// Traverse in reverse order
for (int c = cap; c > 0; c--) {
if (weight[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 - weight[i - 1]] + val[i - 1]);
}
}
}
return dp[cap];
}
[Test]
public void Test() {
int[] weight = [10, 20, 30, 40, 50];
int[] val = [50, 120, 150, 210, 240];
int cap = 50;
int n = weight.Length;
// Brute-force search
int res = KnapsackDFS(weight, val, n, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
// Memoization search
int[][] mem = new int[n + 1][];
for (int i = 0; i <= n; i++) {
mem[i] = new int[cap + 1];
Array.Fill(mem[i], -1);
}
res = KnapsackDFSMem(weight, val, mem, n, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
// Dynamic programming
res = KnapsackDP(weight, val, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
// Space-optimized dynamic programming
res = KnapsackDPComp(weight, val, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
}
}
@@ -0,0 +1,53 @@
/**
* File: min_cost_climbing_stairs_dp.cs
* Created Time: 2023-06-30
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class min_cost_climbing_stairs_dp {
/* Minimum cost climbing stairs: Dynamic programming */
int MinCostClimbingStairsDP(int[] cost) {
int n = cost.Length - 1;
if (n == 1 || n == 2)
return cost[n];
// Initialize dp table, used to store solutions to subproblems
int[] dp = new int[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 (int 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 */
int MinCostClimbingStairsDPComp(int[] cost) {
int n = cost.Length - 1;
if (n == 1 || n == 2)
return cost[n];
int a = cost[1], b = cost[2];
for (int i = 3; i <= n; i++) {
int tmp = b;
b = Math.Min(a, tmp) + cost[i];
a = tmp;
}
return b;
}
[Test]
public void Test() {
int[] cost = [0, 1, 10, 1, 1, 1, 10, 1, 1, 10, 1];
Console.WriteLine("Input stair cost list is");
PrintUtil.PrintList(cost);
int res = MinCostClimbingStairsDP(cost);
Console.WriteLine($"Minimum cost to climb stairs is {res}");
res = MinCostClimbingStairsDPComp(cost);
Console.WriteLine($"Minimum cost to climb stairs is {res}");
}
}
@@ -0,0 +1,127 @@
/**
* File: min_path_sum.cs
* Created Time: 2023-07-10
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class min_path_sum {
/* Minimum path sum: Brute-force search */
int MinPathSumDFS(int[][] grid, int i, int j) {
// 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 int.MaxValue;
}
// Calculate the minimum path cost from top-left to (i-1, j) and (i, j-1)
int up = MinPathSumDFS(grid, i - 1, j);
int 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 */
int MinPathSumDFSMem(int[][] grid, int[][] mem, int i, int j) {
// 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 int.MaxValue;
}
// 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
int up = MinPathSumDFSMem(grid, mem, i - 1, j);
int 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 */
int MinPathSumDP(int[][] grid) {
int n = grid.Length, m = grid[0].Length;
// Initialize dp table
int[,] dp = new int[n, m];
dp[0, 0] = grid[0][0];
// State transition: first row
for (int j = 1; j < m; j++) {
dp[0, j] = dp[0, j - 1] + grid[0][j];
}
// State transition: first column
for (int i = 1; i < n; i++) {
dp[i, 0] = dp[i - 1, 0] + grid[i][0];
}
// State transition: rest of the rows and columns
for (int i = 1; i < n; i++) {
for (int j = 1; j < m; j++) {
dp[i, j] = Math.Min(dp[i, j - 1], dp[i - 1, j]) + grid[i][j];
}
}
return dp[n - 1, m - 1];
}
/* Minimum path sum: Space-optimized dynamic programming */
int MinPathSumDPComp(int[][] grid) {
int n = grid.Length, m = grid[0].Length;
// Initialize dp table
int[] dp = new int[m];
dp[0] = grid[0][0];
// State transition: first row
for (int j = 1; j < m; j++) {
dp[j] = dp[j - 1] + grid[0][j];
}
// State transition: rest of the rows
for (int i = 1; i < n; i++) {
// State transition: first column
dp[0] = dp[0] + grid[i][0];
// State transition: rest of the columns
for (int j = 1; j < m; j++) {
dp[j] = Math.Min(dp[j - 1], dp[j]) + grid[i][j];
}
}
return dp[m - 1];
}
[Test]
public void Test() {
int[][] grid =
[
[1, 3, 1, 5],
[2, 2, 4, 2],
[5, 3, 2, 1],
[4, 3, 5, 2]
];
int n = grid.Length, m = grid[0].Length;
// Brute-force search
int res = MinPathSumDFS(grid, n - 1, m - 1);
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
// Memoization search
int[][] mem = new int[n][];
for (int i = 0; i < n; i++) {
mem[i] = new int[m];
Array.Fill(mem[i], -1);
}
res = MinPathSumDFSMem(grid, mem, n - 1, m - 1);
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
// Dynamic programming
res = MinPathSumDP(grid);
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
// Space-optimized dynamic programming
res = MinPathSumDPComp(grid);
Console.WriteLine("Minimum path sum from top-left to bottom-right is " + res);
}
}
@@ -0,0 +1,64 @@
/**
* File: unbounded_knapsack.cs
* Created Time: 2023-07-12
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_dynamic_programming;
public class unbounded_knapsack {
/* Unbounded knapsack: Dynamic programming */
int UnboundedKnapsackDP(int[] wgt, int[] val, int cap) {
int n = wgt.Length;
// Initialize dp table
int[,] dp = new int[n + 1, cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int 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 */
int UnboundedKnapsackDPComp(int[] wgt, int[] val, int cap) {
int n = wgt.Length;
// Initialize dp table
int[] dp = new int[cap + 1];
// State transition
for (int i = 1; i <= n; i++) {
for (int 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];
}
[Test]
public void Test() {
int[] wgt = [1, 2, 3];
int[] val = [5, 11, 15];
int cap = 4;
// Dynamic programming
int res = UnboundedKnapsackDP(wgt, val, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
// Space-optimized dynamic programming
res = UnboundedKnapsackDPComp(wgt, val, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
}
}
@@ -0,0 +1,122 @@
/**
* File: graph_adjacency_list.cs
* Created Time: 2023-02-06
* Author: zjkung1123 (zjkung1123@gmail.com)
*/
namespace hello_algo.chapter_graph;
/* Undirected graph class based on adjacency list */
public class GraphAdjList {
// Adjacency list, key: vertex, value: all adjacent vertices of that vertex
public Dictionary<Vertex, List<Vertex>> adjList;
/* Constructor */
public GraphAdjList(Vertex[][] edges) {
adjList = [];
// Add all vertices and edges
foreach (Vertex[] edge in edges) {
AddVertex(edge[0]);
AddVertex(edge[1]);
AddEdge(edge[0], edge[1]);
}
}
/* Get the number of vertices */
int Size() {
return adjList.Count;
}
/* Add edge */
public void AddEdge(Vertex vet1, Vertex vet2) {
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
throw new InvalidOperationException();
// Add edge vet1 - vet2
adjList[vet1].Add(vet2);
adjList[vet2].Add(vet1);
}
/* Remove edge */
public void RemoveEdge(Vertex vet1, Vertex vet2) {
if (!adjList.ContainsKey(vet1) || !adjList.ContainsKey(vet2) || vet1 == vet2)
throw new InvalidOperationException();
// Remove edge vet1 - vet2
adjList[vet1].Remove(vet2);
adjList[vet2].Remove(vet1);
}
/* Add vertex */
public void AddVertex(Vertex vet) {
if (adjList.ContainsKey(vet))
return;
// Add a new linked list in the adjacency list
adjList.Add(vet, []);
}
/* Remove vertex */
public void RemoveVertex(Vertex vet) {
if (!adjList.ContainsKey(vet))
throw new InvalidOperationException();
// Remove the linked list corresponding to vertex vet in the adjacency list
adjList.Remove(vet);
// Traverse the linked lists of other vertices and remove all edges containing vet
foreach (List<Vertex> list in adjList.Values) {
list.Remove(vet);
}
}
/* Print adjacency list */
public void Print() {
Console.WriteLine("Adjacency list =");
foreach (KeyValuePair<Vertex, List<Vertex>> pair in adjList) {
List<int> tmp = [];
foreach (Vertex vertex in pair.Value)
tmp.Add(vertex.val);
Console.WriteLine(pair.Key.val + ": [" + string.Join(", ", tmp) + "],");
}
}
}
public class graph_adjacency_list {
[Test]
public void Test() {
/* Add edge */
Vertex[] v = Vertex.ValsToVets([1, 3, 2, 5, 4]);
Vertex[][] edges =
[
[v[0], v[1]],
[v[0], v[3]],
[v[1], v[2]],
[v[2], v[3]],
[v[2], v[4]],
[v[3], v[4]]
];
GraphAdjList graph = new(edges);
Console.WriteLine("\nAfter initialization, graph is");
graph.Print();
/* Add edge */
// Vertices 1, 3 are v[0], v[1]
graph.AddEdge(v[0], v[2]);
Console.WriteLine("\nAfter adding edge 1-2, graph is");
graph.Print();
/* Remove edge */
// Vertex 3 is v[1]
graph.RemoveEdge(v[0], v[1]);
Console.WriteLine("\nAfter removing edge 1-3, graph is");
graph.Print();
/* Add vertex */
Vertex v5 = new(6);
graph.AddVertex(v5);
Console.WriteLine("\nAfter adding vertex 6, graph is");
graph.Print();
/* Remove vertex */
// Vertex 3 is v[1]
graph.RemoveVertex(v[1]);
Console.WriteLine("\nAfter removing vertex 3, graph is");
graph.Print();
}
}
@@ -0,0 +1,137 @@
/**
* File: graph_adjacency_matrix.cs
* Created Time: 2023-02-06
* Author: zjkung1123 (zjkung1123@gmail.com)
*/
namespace hello_algo.chapter_graph;
/* Undirected graph class based on adjacency matrix */
class GraphAdjMat {
List<int> vertices; // Vertex list, where the element represents the "vertex value" and the index represents the "vertex index"
List<List<int>> adjMat; // Adjacency matrix, where the row and column indices correspond to the "vertex index"
/* Constructor */
public GraphAdjMat(int[] vertices, int[][] edges) {
this.vertices = [];
this.adjMat = [];
// Add vertex
foreach (int val in vertices) {
AddVertex(val);
}
// Add edge
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
foreach (int[] e in edges) {
AddEdge(e[0], e[1]);
}
}
/* Get the number of vertices */
int Size() {
return vertices.Count;
}
/* Add vertex */
public void AddVertex(int val) {
int n = Size();
// Add the value of the new vertex to the vertex list
vertices.Add(val);
// Add a row to the adjacency matrix
List<int> newRow = new(n);
for (int j = 0; j < n; j++) {
newRow.Add(0);
}
adjMat.Add(newRow);
// Add a column to the adjacency matrix
foreach (List<int> row in adjMat) {
row.Add(0);
}
}
/* Remove vertex */
public void RemoveVertex(int index) {
if (index >= Size())
throw new IndexOutOfRangeException();
// Remove the vertex at index from the vertex list
vertices.RemoveAt(index);
// Remove the row at index from the adjacency matrix
adjMat.RemoveAt(index);
// Remove the column at index from the adjacency matrix
foreach (List<int> row in adjMat) {
row.RemoveAt(index);
}
}
/* Add edge */
// Parameters i, j correspond to the vertices element indices
public void AddEdge(int i, int j) {
// Handle index out of bounds and equality
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
throw new IndexOutOfRangeException();
// In an undirected graph, the adjacency matrix is symmetric about the main diagonal, i.e., (i, j) == (j, i)
adjMat[i][j] = 1;
adjMat[j][i] = 1;
}
/* Remove edge */
// Parameters i, j correspond to the vertices element indices
public void RemoveEdge(int i, int j) {
// Handle index out of bounds and equality
if (i < 0 || j < 0 || i >= Size() || j >= Size() || i == j)
throw new IndexOutOfRangeException();
adjMat[i][j] = 0;
adjMat[j][i] = 0;
}
/* Print adjacency matrix */
public void Print() {
Console.Write("Vertex list = ");
PrintUtil.PrintList(vertices);
Console.WriteLine("Adjacency matrix =");
PrintUtil.PrintMatrix(adjMat);
}
}
public class graph_adjacency_matrix {
[Test]
public void Test() {
/* Add edge */
// Note that the edges elements represent vertex indices, i.e., corresponding to the vertices element indices
int[] vertices = [1, 3, 2, 5, 4];
int[][] edges =
[
[0, 1],
[0, 3],
[1, 2],
[2, 3],
[2, 4],
[3, 4]
];
GraphAdjMat graph = new(vertices, edges);
Console.WriteLine("\nAfter initialization, graph is");
graph.Print();
/* Add edge */
// Add vertex
graph.AddEdge(0, 2);
Console.WriteLine("\nAfter adding edge 1-2, graph is");
graph.Print();
/* Remove edge */
// Vertices 1, 3 have indices 0, 1 respectively
graph.RemoveEdge(0, 1);
Console.WriteLine("\nAfter removing edge 1-3, graph is");
graph.Print();
/* Add vertex */
graph.AddVertex(6);
Console.WriteLine("\nAfter adding vertex 6, graph is");
graph.Print();
/* Remove vertex */
// Vertex 3 has index 1
graph.RemoveVertex(1);
Console.WriteLine("\nAfter removing vertex 3, graph is");
graph.Print();
}
}
@@ -0,0 +1,58 @@
/**
* File: graph_bfs.cs
* Created Time: 2023-03-08
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_graph;
public class graph_bfs {
/* Breadth-first traversal */
// Use adjacency list to represent the graph, in order to obtain all adjacent vertices of a specified vertex
List<Vertex> GraphBFS(GraphAdjList graph, Vertex startVet) {
// Vertex traversal sequence
List<Vertex> res = [];
// Hash set for recording vertices that have been visited
HashSet<Vertex> visited = [startVet];
// Queue used to implement BFS
Queue<Vertex> que = new();
que.Enqueue(startVet);
// Starting from vertex vet, loop until all vertices are visited
while (que.Count > 0) {
Vertex vet = que.Dequeue(); // Dequeue the front vertex
res.Add(vet); // Record visited vertex
foreach (Vertex adjVet in graph.adjList[vet]) {
if (visited.Contains(adjVet)) {
continue; // Skip vertices that have been visited
}
que.Enqueue(adjVet); // Only enqueue unvisited vertices
visited.Add(adjVet); // Mark this vertex as visited
}
}
// Return vertex traversal sequence
return res;
}
[Test]
public void Test() {
/* Add edge */
Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]);
Vertex[][] 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]]
];
GraphAdjList graph = new(edges);
Console.WriteLine("\nAfter initialization, graph is");
graph.Print();
/* Breadth-first traversal */
List<Vertex> res = GraphBFS(graph, v[0]);
Console.WriteLine("\nBreadth-first traversal (BFS) vertex sequence is");
Console.WriteLine(string.Join(" ", Vertex.VetsToVals(res)));
}
}
@@ -0,0 +1,54 @@
/**
* File: graph_dfs.cs
* Created Time: 2023-03-08
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_graph;
public class graph_dfs {
/* Depth-first traversal helper function */
void DFS(GraphAdjList graph, HashSet<Vertex> visited, List<Vertex> res, Vertex vet) {
res.Add(vet); // Record visited vertex
visited.Add(vet); // Mark this vertex as visited
// Traverse all adjacent vertices of this vertex
foreach (Vertex adjVet in graph.adjList[vet]) {
if (visited.Contains(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
List<Vertex> GraphDFS(GraphAdjList graph, Vertex startVet) {
// Vertex traversal sequence
List<Vertex> res = [];
// Hash set for recording vertices that have been visited
HashSet<Vertex> visited = [];
DFS(graph, visited, res, startVet);
return res;
}
[Test]
public void Test() {
/* Add edge */
Vertex[] v = Vertex.ValsToVets([0, 1, 2, 3, 4, 5, 6]);
Vertex[][] 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]],
];
GraphAdjList graph = new(edges);
Console.WriteLine("\nAfter initialization, graph is");
graph.Print();
/* Depth-first traversal */
List<Vertex> res = GraphDFS(graph, v[0]);
Console.WriteLine("\nDepth-first traversal (DFS) vertex sequence is");
Console.WriteLine(string.Join(" ", Vertex.VetsToVals(res)));
}
}
@@ -0,0 +1,54 @@
/**
* File: coin_change_greedy.cs
* Created Time: 2023-07-21
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_greedy;
public class coin_change_greedy {
/* Coin change: Greedy algorithm */
int CoinChangeGreedy(int[] coins, int amt) {
// Assume coins list is sorted
int i = coins.Length - 1;
int 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;
}
[Test]
public void Test() {
// Greedy algorithm: Can guarantee finding the global optimal solution
int[] coins = [1, 5, 10, 20, 50, 100];
int amt = 186;
int res = CoinChangeGreedy(coins, amt);
Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
Console.WriteLine("To make " + amt + ", minimum number of coins needed is " + res);
// Greedy algorithm: Cannot guarantee finding the global optimal solution
coins = [1, 20, 50];
amt = 60;
res = CoinChangeGreedy(coins, amt);
Console.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
Console.WriteLine("To make " + amt + ", minimum number of coins needed is " + res);
Console.WriteLine("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.WriteLine("\ncoins = " + coins.PrintList() + ", amt = " + amt);
Console.WriteLine("To make " + amt + ", minimum number of coins needed is " + res);
Console.WriteLine("Actually the minimum number needed is 2, i.e., 49 + 49");
}
}
@@ -0,0 +1,52 @@
/**
* File: fractional_knapsack.cs
* Created Time: 2023-07-21
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_greedy;
/* Item */
class Item(int w, int v) {
public int w = w; // Item weight
public int v = v; // Item value
}
public class fractional_knapsack {
/* Fractional knapsack: Greedy algorithm */
double FractionalKnapsack(int[] wgt, int[] val, int cap) {
// Create item list with two attributes: weight, value
Item[] items = new Item[wgt.Length];
for (int i = 0; i < wgt.Length; i++) {
items[i] = new Item(wgt[i], val[i]);
}
// Sort by unit value item.v / item.w from high to low
Array.Sort(items, (x, y) => (y.v / y.w).CompareTo(x.v / x.w));
// Loop for greedy selection
double res = 0;
foreach (Item item in 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 += (double)item.v / item.w * cap;
// No remaining capacity, so break out of the loop
break;
}
}
return res;
}
[Test]
public void Test() {
int[] wgt = [10, 20, 30, 40, 50];
int[] val = [50, 120, 150, 210, 240];
int cap = 50;
// Greedy algorithm
double res = FractionalKnapsack(wgt, val, cap);
Console.WriteLine("Maximum item value not exceeding knapsack capacity is " + res);
}
}
@@ -0,0 +1,39 @@
/**
* File: max_capacity.cs
* Created Time: 2023-07-21
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_greedy;
public class max_capacity {
/* Max capacity: Greedy algorithm */
int MaxCapacity(int[] ht) {
// Initialize i, j to be at both ends of the array
int i = 0, j = ht.Length - 1;
// Initial max capacity is 0
int res = 0;
// Loop for greedy selection until the two boards meet
while (i < j) {
// Update max capacity
int cap = Math.Min(ht[i], ht[j]) * (j - i);
res = Math.Max(res, cap);
// Move the shorter board inward
if (ht[i] < ht[j]) {
i++;
} else {
j--;
}
}
return res;
}
[Test]
public void Test() {
int[] ht = [3, 8, 5, 2, 7, 7, 3, 4];
// Greedy algorithm
int res = MaxCapacity(ht);
Console.WriteLine("Maximum capacity is " + res);
}
}
@@ -0,0 +1,39 @@
/**
* File: max_product_cutting.cs
* Created Time: 2023-07-21
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_greedy;
public class max_product_cutting {
/* Max product cutting: Greedy algorithm */
int MaxProductCutting(int n) {
// 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
int a = n / 3;
int b = n % 3;
if (b == 1) {
// When the remainder is 1, convert a pair of 1 * 3 to 2 * 2
return (int)Math.Pow(3, a - 1) * 2 * 2;
}
if (b == 2) {
// When the remainder is 2, do nothing
return (int)Math.Pow(3, a) * 2;
}
// When the remainder is 0, do nothing
return (int)Math.Pow(3, a);
}
[Test]
public void Test() {
int n = 58;
// Greedy algorithm
int res = MaxProductCutting(n);
Console.WriteLine("Maximum cutting product is" + res);
}
}
@@ -0,0 +1,134 @@
/**
* File: array_hash_map.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_hashing;
/* Key-value pair int->string */
class Pair(int key, string val) {
public int key = key;
public string val = val;
}
/* Hash table based on array implementation */
class ArrayHashMap {
List<Pair?> buckets;
public ArrayHashMap() {
// Initialize array with 100 buckets
buckets = [];
for (int i = 0; i < 100; i++) {
buckets.Add(null);
}
}
/* Hash function */
int HashFunc(int key) {
int index = key % 100;
return index;
}
/* Query operation */
public string? Get(int key) {
int index = HashFunc(key);
Pair? pair = buckets[index];
if (pair == null) return null;
return pair.val;
}
/* Add operation */
public void Put(int key, string val) {
Pair pair = new(key, val);
int index = HashFunc(key);
buckets[index] = pair;
}
/* Remove operation */
public void Remove(int key) {
int index = HashFunc(key);
// Set to null to represent deletion
buckets[index] = null;
}
/* Get all key-value pairs */
public List<Pair> PairSet() {
List<Pair> pairSet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
pairSet.Add(pair);
}
return pairSet;
}
/* Get all keys */
public List<int> KeySet() {
List<int> keySet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
keySet.Add(pair.key);
}
return keySet;
}
/* Get all values */
public List<string> ValueSet() {
List<string> valueSet = [];
foreach (Pair? pair in buckets) {
if (pair != null)
valueSet.Add(pair.val);
}
return valueSet;
}
/* Print hash table */
public void Print() {
foreach (Pair kv in PairSet()) {
Console.WriteLine(kv.key + " -> " + kv.val);
}
}
}
public class array_hash_map {
[Test]
public void Test() {
/* Initialize hash table */
ArrayHashMap map = new();
/* 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.WriteLine("\nAfter adding is complete, hash table is\nKey -> Value");
map.Print();
/* Query operation */
// Input key into hash table to get value
string? name = map.Get(15937);
Console.WriteLine("\nInput student ID 15937, query name " + name);
/* Remove operation */
// Remove key-value pair (key, value) from hash table
map.Remove(10583);
Console.WriteLine("\nAfter removing 10583, hash table is\nKey -> Value");
map.Print();
/* Traverse hash table */
Console.WriteLine("\nTraverse key-value pairs Key->Value");
foreach (Pair kv in map.PairSet()) {
Console.WriteLine(kv.key + " -> " + kv.val);
}
Console.WriteLine("\nTraverse keys only Key");
foreach (int key in map.KeySet()) {
Console.WriteLine(key);
}
Console.WriteLine("\nTraverse values only Value");
foreach (string val in map.ValueSet()) {
Console.WriteLine(val);
}
}
}
@@ -0,0 +1,36 @@
/**
* File: built_in_hash.cs
* Created Time: 2023-06-26
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
public class built_in_hash {
[Test]
public void Test() {
int num = 3;
int hashNum = num.GetHashCode();
Console.WriteLine("Integer " + num + " has hash value " + hashNum);
bool bol = true;
int hashBol = bol.GetHashCode();
Console.WriteLine("Boolean " + bol + " has hash value " + hashBol);
double dec = 3.14159;
int hashDec = dec.GetHashCode();
Console.WriteLine("Decimal " + dec + " has hash value " + hashDec);
string str = "Hello Algo";
int hashStr = str.GetHashCode();
Console.WriteLine("String " + str + " has hash value " + hashStr);
object[] arr = [12836, "Xiao Ha"];
int hashTup = arr.GetHashCode();
Console.WriteLine("Array [" + string.Join(", ", arr) + "] hash value is " + hashTup);
ListNode obj = new(0);
int hashObj = obj.GetHashCode();
Console.WriteLine("Node object " + obj + " has hash value " + hashObj);
}
}
@@ -0,0 +1,51 @@
/**
* File: hash_map.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_hashing;
public class hash_map {
[Test]
public void Test() {
/* Initialize hash table */
Dictionary<int, string> map = new() {
/* Add operation */
// Add key-value pair (key, value) to the hash table
{ 12836, "Xiao Ha" },
{ 15937, "Xiao Luo" },
{ 16750, "Xiao Suan" },
{ 13276, "Xiao Fa" },
{ 10583, "Xiao Ya" }
};
Console.WriteLine("\nAfter adding is complete, hash table is\nKey -> Value");
PrintUtil.PrintHashMap(map);
/* Query operation */
// Input key into hash table to get value
string name = map[15937];
Console.WriteLine("\nInput student ID 15937, query name " + name);
/* Remove operation */
// Remove key-value pair (key, value) from hash table
map.Remove(10583);
Console.WriteLine("\nAfter removing 10583, hash table is\nKey -> Value");
PrintUtil.PrintHashMap(map);
/* Traverse hash table */
Console.WriteLine("\nTraverse key-value pairs Key->Value");
foreach (var kv in map) {
Console.WriteLine(kv.Key + " -> " + kv.Value);
}
Console.WriteLine("\nTraverse keys only Key");
foreach (int key in map.Keys) {
Console.WriteLine(key);
}
Console.WriteLine("\nTraverse values only Value");
foreach (string val in map.Values) {
Console.WriteLine(val);
}
}
}
@@ -0,0 +1,144 @@
/**
* File: hash_map_chaining.cs
* Created Time: 2023-06-26
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
/* Hash table with separate chaining */
class HashMapChaining {
int size; // Number of key-value pairs
int capacity; // Hash table capacity
double loadThres; // Load factor threshold for triggering expansion
int extendRatio; // Expansion multiplier
List<List<Pair>> buckets; // Bucket array
/* Constructor */
public HashMapChaining() {
size = 0;
capacity = 4;
loadThres = 2.0 / 3.0;
extendRatio = 2;
buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.Add([]);
}
}
/* Hash function */
int HashFunc(int key) {
return key % capacity;
}
/* Load factor */
double LoadFactor() {
return (double)size / capacity;
}
/* Query operation */
public string? Get(int key) {
int index = HashFunc(key);
// Traverse bucket, if key is found, return corresponding val
foreach (Pair pair in buckets[index]) {
if (pair.key == key) {
return pair.val;
}
}
// If key is not found, return null
return null;
}
/* Add operation */
public void Put(int key, string val) {
// When load factor exceeds threshold, perform expansion
if (LoadFactor() > loadThres) {
Extend();
}
int index = HashFunc(key);
// Traverse bucket, if specified key is encountered, update corresponding val and return
foreach (Pair pair in buckets[index]) {
if (pair.key == key) {
pair.val = val;
return;
}
}
// If key does not exist, append key-value pair to the end
buckets[index].Add(new Pair(key, val));
size++;
}
/* Remove operation */
public void Remove(int key) {
int index = HashFunc(key);
// Traverse bucket and remove key-value pair from it
foreach (Pair pair in buckets[index].ToList()) {
if (pair.key == key) {
buckets[index].Remove(pair);
size--;
break;
}
}
}
/* Expand hash table */
void Extend() {
// Temporarily store the original hash table
List<List<Pair>> bucketsTmp = buckets;
// Initialize expanded new hash table
capacity *= extendRatio;
buckets = new List<List<Pair>>(capacity);
for (int i = 0; i < capacity; i++) {
buckets.Add([]);
}
size = 0;
// Move key-value pairs from original hash table to new hash table
foreach (List<Pair> bucket in bucketsTmp) {
foreach (Pair pair in bucket) {
Put(pair.key, pair.val);
}
}
}
/* Print hash table */
public void Print() {
foreach (List<Pair> bucket in buckets) {
List<string> res = [];
foreach (Pair pair in bucket) {
res.Add(pair.key + " -> " + pair.val);
}
foreach (string kv in res) {
Console.WriteLine(kv);
}
}
}
}
public class hash_map_chaining {
[Test]
public void Test() {
/* Initialize hash table */
HashMapChaining map = new();
/* 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.WriteLine("\nAfter adding is complete, hash table is\nKey -> Value");
map.Print();
/* Query operation */
// Input key into hash table to get value
string? name = map.Get(13276);
Console.WriteLine("\nInput student ID 13276, query name " + name);
/* Remove operation */
// Remove key-value pair (key, value) from hash table
map.Remove(12836);
Console.WriteLine("\nAfter removing 12836, hash table is\nKey -> Value");
map.Print();
}
}
@@ -0,0 +1,159 @@
/**
* File: hash_map_open_addressing.cs
* Created Time: 2023-06-26
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
/* Hash table with open addressing */
class HashMapOpenAddressing {
int size; // Number of key-value pairs
int capacity = 4; // Hash table capacity
double loadThres = 2.0 / 3.0; // Load factor threshold for triggering expansion
int extendRatio = 2; // Expansion multiplier
Pair[] buckets; // Bucket array
Pair TOMBSTONE = new(-1, "-1"); // Removal marker
/* Constructor */
public HashMapOpenAddressing() {
size = 0;
buckets = new Pair[capacity];
}
/* Hash function */
int HashFunc(int key) {
return key % capacity;
}
/* Load factor */
double LoadFactor() {
return (double)size / capacity;
}
/* Search for bucket index corresponding to key */
int FindBucket(int key) {
int index = HashFunc(key);
int firstTombstone = -1;
// Linear probing, break when encountering an empty bucket
while (buckets[index] != null) {
// If key is encountered, return the corresponding bucket index
if (buckets[index].key == key) {
// If a removal marker was encountered before, move the key-value pair to that index
if (firstTombstone != -1) {
buckets[firstTombstone] = buckets[index];
buckets[index] = TOMBSTONE;
return firstTombstone; // Return the moved bucket index
}
return index; // Return bucket index
}
// Record the first removal marker encountered
if (firstTombstone == -1 && buckets[index] == TOMBSTONE) {
firstTombstone = index;
}
// Calculate bucket index, wrap around to the head if past the tail
index = (index + 1) % capacity;
}
// If key does not exist, return the index for insertion
return firstTombstone == -1 ? index : firstTombstone;
}
/* Query operation */
public string? Get(int key) {
// Search for bucket index corresponding to key
int index = FindBucket(key);
// If key-value pair is found, return corresponding val
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
return buckets[index].val;
}
// If key-value pair does not exist, return null
return null;
}
/* Add operation */
public void Put(int key, string val) {
// When load factor exceeds threshold, perform expansion
if (LoadFactor() > loadThres) {
Extend();
}
// Search for bucket index corresponding to key
int index = FindBucket(key);
// If key-value pair is found, overwrite val and return
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
buckets[index].val = val;
return;
}
// If key-value pair does not exist, add the key-value pair
buckets[index] = new Pair(key, val);
size++;
}
/* Remove operation */
public void Remove(int key) {
// Search for bucket index corresponding to key
int index = FindBucket(key);
// If key-value pair is found, overwrite it with removal marker
if (buckets[index] != null && buckets[index] != TOMBSTONE) {
buckets[index] = TOMBSTONE;
size--;
}
}
/* Expand hash table */
void Extend() {
// Temporarily store the original hash table
Pair[] bucketsTmp = buckets;
// Initialize expanded new hash table
capacity *= extendRatio;
buckets = new Pair[capacity];
size = 0;
// Move key-value pairs from original hash table to new hash table
foreach (Pair pair in bucketsTmp) {
if (pair != null && pair != TOMBSTONE) {
Put(pair.key, pair.val);
}
}
}
/* Print hash table */
public void Print() {
foreach (Pair pair in buckets) {
if (pair == null) {
Console.WriteLine("null");
} else if (pair == TOMBSTONE) {
Console.WriteLine("TOMBSTONE");
} else {
Console.WriteLine(pair.key + " -> " + pair.val);
}
}
}
}
public class hash_map_open_addressing {
[Test]
public void Test() {
/* Initialize hash table */
HashMapOpenAddressing map = new();
/* 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.WriteLine("\nAfter adding is complete, hash table is\nKey -> Value");
map.Print();
/* Query operation */
// Input key into hash table to get value
string? name = map.Get(13276);
Console.WriteLine("\nInput student ID 13276, query name " + name);
/* Remove operation */
// Remove key-value pair (key, value) from hash table
map.Remove(16750);
Console.WriteLine("\nAfter removing 16750, hash table is\nKey -> Value");
map.Print();
}
}
@@ -0,0 +1,66 @@
/**
* File: simple_hash.cs
* Created Time: 2023-06-26
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_hashing;
public class simple_hash {
/* Additive hash */
int AddHash(string key) {
long hash = 0;
const int MODULUS = 1000000007;
foreach (char c in key) {
hash = (hash + c) % MODULUS;
}
return (int)hash;
}
/* Multiplicative hash */
int MulHash(string key) {
long hash = 0;
const int MODULUS = 1000000007;
foreach (char c in key) {
hash = (31 * hash + c) % MODULUS;
}
return (int)hash;
}
/* XOR hash */
int XorHash(string key) {
int hash = 0;
const int MODULUS = 1000000007;
foreach (char c in key) {
hash ^= c;
}
return hash & MODULUS;
}
/* Rotational hash */
int RotHash(string key) {
long hash = 0;
const int MODULUS = 1000000007;
foreach (char c in key) {
hash = ((hash << 4) ^ (hash >> 28) ^ c) % MODULUS;
}
return (int)hash;
}
[Test]
public void Test() {
string key = "Hello Algo";
int hash = AddHash(key);
Console.WriteLine("Additive hash value is " + hash);
hash = MulHash(key);
Console.WriteLine("Multiplicative hash value is " + hash);
hash = XorHash(key);
Console.WriteLine("XOR hash value is " + hash);
hash = RotHash(key);
Console.WriteLine("Rotational hash value is " + hash);
}
}
+64
View File
@@ -0,0 +1,64 @@
/**
* File: heap.cs
* Created Time: 2023-02-06
* Author: zjkung1123 (zjkung1123@gmail.com)
*/
namespace hello_algo.chapter_heap;
public class heap {
void TestPush(PriorityQueue<int, int> heap, int val) {
heap.Enqueue(val, val); // Element enters heap
Console.WriteLine($"\nAfter element {val} pushes to heap\n");
PrintUtil.PrintHeap(heap);
}
void TestPop(PriorityQueue<int, int> heap) {
int val = heap.Dequeue(); // Time complexity is O(n), not O(nlogn)
Console.WriteLine($"\nAfter heap top element {val} pops from heap\n");
PrintUtil.PrintHeap(heap);
}
[Test]
public void Test() {
/* Initialize heap */
// Python's heapq module implements min heap by default
PriorityQueue<int, int> minHeap = new();
// Initialize max heap (modify Comparer using lambda expression)
PriorityQueue<int, int> maxHeap = new(Comparer<int>.Create((x, y) => y.CompareTo(x)));
Console.WriteLine("Following test cases are for max heap");
/* Element enters heap */
TestPush(maxHeap, 1);
TestPush(maxHeap, 3);
TestPush(maxHeap, 2);
TestPush(maxHeap, 5);
TestPush(maxHeap, 4);
/* Check if heap is empty */
int peek = maxHeap.Peek();
Console.WriteLine($"Heap top element is {peek}");
/* Time complexity is O(n), not O(nlogn) */
// Dequeued elements form a descending sequence
TestPop(maxHeap);
TestPop(maxHeap);
TestPop(maxHeap);
TestPop(maxHeap);
TestPop(maxHeap);
/* Get heap size */
int size = maxHeap.Count;
Console.WriteLine($"Heap size is {size}");
/* Check if heap is empty */
bool isEmpty = maxHeap.Count == 0;
Console.WriteLine($"Is heap empty {isEmpty}");
/* Input list and build heap */
var list = new int[] { 1, 3, 2, 5, 4 };
minHeap = new PriorityQueue<int, int>(list.Select(x => (x, x)));
Console.WriteLine("After input list and building min heap");
PrintUtil.PrintHeap(minHeap);
}
}
+160
View File
@@ -0,0 +1,160 @@
/**
* File: my_heap.cs
* Created Time: 2023-02-06
* Author: zjkung1123 (zjkung1123@gmail.com)
*/
namespace hello_algo.chapter_heap;
/* Max heap */
class MaxHeap {
// Use list instead of array, no need to consider capacity expansion
List<int> maxHeap;
/* Constructor, build empty heap */
public MaxHeap() {
maxHeap = [];
}
/* Constructor, build heap from input list */
public MaxHeap(IEnumerable<int> nums) {
// Add list elements to heap as is
maxHeap = new List<int>(nums);
// Heapify all nodes except leaf nodes
var size = Parent(this.Size() - 1);
for (int i = size; i >= 0; i--) {
SiftDown(i);
}
}
/* Get index of left child node */
int Left(int i) {
return 2 * i + 1;
}
/* Get index of right child node */
int Right(int i) {
return 2 * i + 2;
}
/* Get index of parent node */
int Parent(int i) {
return (i - 1) / 2; // Floor division
}
/* Access top element */
public int Peek() {
return maxHeap[0];
}
/* Element enters heap */
public void Push(int val) {
// Add node
maxHeap.Add(val);
// Heapify from bottom to top
SiftUp(Size() - 1);
}
/* Get heap size */
public int Size() {
return maxHeap.Count;
}
/* Check if heap is empty */
public bool IsEmpty() {
return Size() == 0;
}
/* Starting from node i, heapify from bottom to top */
void SiftUp(int i) {
while (true) {
// Get parent node of node i
int p = Parent(i);
// If 'past root node' or 'node needs no repair', end heapify
if (p < 0 || maxHeap[i] <= maxHeap[p])
break;
// Swap two nodes
Swap(i, p);
// Loop upward heapify
i = p;
}
}
/* Element exits heap */
public int Pop() {
// Handle empty case
if (IsEmpty())
throw new IndexOutOfRangeException();
// Delete node
Swap(0, Size() - 1);
// Remove node
int val = maxHeap.Last();
maxHeap.RemoveAt(Size() - 1);
// Return top element
SiftDown(0);
// Return heap top element
return val;
}
/* Starting from node i, heapify from top to bottom */
void SiftDown(int i) {
while (true) {
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
int l = Left(i), r = Right(i), ma = i;
if (l < Size() && maxHeap[l] > maxHeap[ma])
ma = l;
if (r < Size() && maxHeap[r] > maxHeap[ma])
ma = r;
// If 'node i is largest' or 'past leaf node', end heapify
if (ma == i) break;
// Swap two nodes
Swap(i, ma);
// Loop downwards heapification
i = ma;
}
}
/* Swap elements */
void Swap(int i, int p) {
(maxHeap[i], maxHeap[p]) = (maxHeap[p], maxHeap[i]);
}
/* Driver Code */
public void Print() {
var queue = new Queue<int>(maxHeap);
PrintUtil.PrintHeap(queue);
}
}
public class my_heap {
[Test]
public void Test() {
/* Consider negating the elements before entering the heap, which can reverse the size relationship, thus implementing max heap */
MaxHeap maxHeap = new([9, 8, 6, 6, 7, 5, 2, 1, 4, 3, 6, 2]);
Console.WriteLine("\nAfter inputting list and building heap");
maxHeap.Print();
/* Check if heap is empty */
int peek = maxHeap.Peek();
Console.WriteLine($"Heap top element is {peek}");
/* Element enters heap */
int val = 7;
maxHeap.Push(val);
Console.WriteLine($"After element {val} pushes to heap");
maxHeap.Print();
/* Time complexity is O(n), not O(nlogn) */
peek = maxHeap.Pop();
Console.WriteLine($"After heap top element {peek} pops from heap");
maxHeap.Print();
/* Get heap size */
int size = maxHeap.Size();
Console.WriteLine($"Heap size is {size}");
/* Check if heap is empty */
bool isEmpty = maxHeap.IsEmpty();
Console.WriteLine($"Is heap empty {isEmpty}");
}
}
+37
View File
@@ -0,0 +1,37 @@
/**
* File: top_k.cs
* Created Time: 2023-06-14
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_heap;
public class top_k {
/* Find the largest k elements in array based on heap */
PriorityQueue<int, int> TopKHeap(int[] nums, int k) {
// Python's heapq module implements min heap by default
PriorityQueue<int, int> heap = new();
// Enter the first k elements of array into heap
for (int i = 0; i < k; i++) {
heap.Enqueue(nums[i], nums[i]);
}
// Starting from the (k+1)th element, maintain heap length as k
for (int 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] > heap.Peek()) {
heap.Dequeue();
heap.Enqueue(nums[i], nums[i]);
}
}
return heap;
}
[Test]
public void Test() {
int[] nums = [1, 7, 6, 3, 2];
int k = 3;
PriorityQueue<int, int> res = TopKHeap(nums, k);
Console.WriteLine("The largest " + k + " elements are");
PrintUtil.PrintHeap(res);
}
}
@@ -0,0 +1,59 @@
/**
* File: binary_search.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_searching;
public class binary_search {
/* Binary search (closed interval on both sides) */
int BinarySearch(int[] nums, int target) {
// Initialize closed interval [0, n-1], i.e., i, j point to the first and last elements of the array
int i = 0, j = nums.Length - 1;
// Loop, exit when the search interval is empty (empty when i > j)
while (i <= j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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;
}
// Target element not found, return -1
return -1;
}
/* Binary search (left-closed right-open interval) */
int BinarySearchLCRO(int[] nums, int target) {
// Initialize left-closed right-open interval [0, n), i.e., i, j point to the first element and last element+1
int i = 0, j = nums.Length;
// Loop, exit when the search interval is empty (empty when i = j)
while (i < j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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;
}
// Target element not found, return -1
return -1;
}
[Test]
public void Test() {
int target = 6;
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
/* Binary search (closed interval on both sides) */
int index = BinarySearch(nums, target);
Console.WriteLine("Index of target element 6 = " + index);
/* Binary search (left-closed right-open interval) */
index = BinarySearchLCRO(nums, target);
Console.WriteLine("Index of target element 6 = " + index);
}
}
@@ -0,0 +1,50 @@
/**
* File: binary_search_edge.cs
* Created Time: 2023-08-06
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_searching;
public class binary_search_edge {
/* Binary search for the leftmost target */
int BinarySearchLeftEdge(int[] nums, int target) {
// Equivalent to finding the insertion point of target
int i = binary_search_insertion.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 */
int BinarySearchRightEdge(int[] nums, int target) {
// Convert to finding the leftmost target + 1
int i = binary_search_insertion.BinarySearchInsertion(nums, target + 1);
// j points to the rightmost target, i points to the first element greater than target
int j = i - 1;
// Target not found, return -1
if (j == -1 || nums[j] != target) {
return -1;
}
// Found target, return index j
return j;
}
[Test]
public void Test() {
// Array with duplicate elements
int[] nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
Console.WriteLine("\nArray nums = " + nums.PrintList());
// Binary search left and right boundaries
foreach (int target in new int[] { 6, 7 }) {
int index = BinarySearchLeftEdge(nums, target);
Console.WriteLine("Leftmost element " + target + " has index " + index);
index = BinarySearchRightEdge(nums, target);
Console.WriteLine("Rightmost element " + target + " has index " + index);
}
}
}
@@ -0,0 +1,64 @@
/**
* File: binary_search_insertion.cs
* Created Time: 2023-08-06
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_searching;
public class binary_search_insertion {
/* Binary search for insertion point (no duplicate elements) */
public static int BinarySearchInsertionSimple(int[] nums, int target) {
int i = 0, j = nums.Length - 1; // Initialize closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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) */
public static int BinarySearchInsertion(int[] nums, int target) {
int i = 0, j = nums.Length - 1; // Initialize closed interval [0, n-1]
while (i <= j) {
int m = i + (j - i) / 2; // Calculate the midpoint index m
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;
}
[Test]
public void Test() {
// Array without duplicate elements
int[] nums = [1, 3, 6, 8, 12, 15, 23, 26, 31, 35];
Console.WriteLine("\nArray nums = " + nums.PrintList());
// Binary search for insertion point
foreach (int target in new int[] { 6, 9 }) {
int index = BinarySearchInsertionSimple(nums, target);
Console.WriteLine("Element " + target + "'s insertion point index is " + index);
}
// Array with duplicate elements
nums = [1, 3, 6, 6, 6, 6, 6, 10, 12, 15];
Console.WriteLine("\nArray nums = " + nums.PrintList());
// Binary search for insertion point
foreach (int target in new int[] { 2, 6, 20 }) {
int index = BinarySearchInsertion(nums, target);
Console.WriteLine("Element " + target + "'s insertion point index is " + index);
}
}
}
@@ -0,0 +1,50 @@
/**
* File: hashing_search.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_searching;
public class hashing_search {
/* Hash search (array) */
int HashingSearchArray(Dictionary<int, int> map, int target) {
// Hash table's key: target element, value: index
// If this key does not exist in the hash table, return -1
return map.GetValueOrDefault(target, -1);
}
/* Hash search (linked list) */
ListNode? HashingSearchLinkedList(Dictionary<int, ListNode> map, int target) {
// Hash table key: target node value, value: node object
// If key is not in hash table, return null
return map.GetValueOrDefault(target);
}
[Test]
public void Test() {
int target = 3;
/* Hash search (array) */
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
// Initialize hash table
Dictionary<int, int> map = [];
for (int i = 0; i < nums.Length; i++) {
map[nums[i]] = i; // key: element, value: index
}
int index = HashingSearchArray(map, target);
Console.WriteLine("Index of target element 3 = " + index);
/* Hash search (linked list) */
ListNode? head = ListNode.ArrToLinkedList(nums);
// Initialize hash table
Dictionary<int, ListNode> map1 = [];
while (head != null) {
map1[head.val] = head; // key: node value, value: node
head = head.next;
}
ListNode? node = HashingSearchLinkedList(map1, target);
Console.WriteLine("Node object corresponding to target node value 3 is " + node);
}
}
@@ -0,0 +1,49 @@
/**
* File: linear_search.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_searching;
public class linear_search {
/* Linear search (array) */
int LinearSearchArray(int[] nums, int target) {
// Traverse array
for (int 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) */
ListNode? LinearSearchLinkedList(ListNode? head, int target) {
// Traverse the linked list
while (head != null) {
// Found the target node, return it
if (head.val == target)
return head;
head = head.next;
}
// Target node not found, return null
return null;
}
[Test]
public void Test() {
int target = 3;
/* Perform linear search in array */
int[] nums = [1, 5, 3, 2, 4, 7, 5, 9, 10, 8];
int index = LinearSearchArray(nums, target);
Console.WriteLine("Index of target element 3 = " + index);
/* Perform linear search in linked list */
ListNode? head = ListNode.ArrToLinkedList(nums);
ListNode? node = LinearSearchLinkedList(head, target);
Console.WriteLine("Node object corresponding to target node value 3 is " + node);
}
}
@@ -0,0 +1,52 @@
/**
* File: two_sum.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_searching;
public class two_sum {
/* Method 1: Brute force enumeration */
int[] TwoSumBruteForce(int[] nums, int target) {
int size = nums.Length;
// Two nested loops, time complexity is O(n^2)
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (nums[i] + nums[j] == target)
return [i, j];
}
}
return [];
}
/* Method 2: Auxiliary hash table */
int[] TwoSumHashTable(int[] nums, int target) {
int size = nums.Length;
// Auxiliary hash table, space complexity is O(n)
Dictionary<int, int> dic = [];
// Single loop, time complexity is O(n)
for (int i = 0; i < size; i++) {
if (dic.ContainsKey(target - nums[i])) {
return [dic[target - nums[i]], i];
}
dic.Add(nums[i], i);
}
return [];
}
[Test]
public void Test() {
// ======= Test Case =======
int[] nums = [2, 7, 11, 15];
int target = 13;
// ====== Driver Code ======
// Method 1
int[] res = TwoSumBruteForce(nums, target);
Console.WriteLine("Method 1 res = " + string.Join(",", res));
// Method 2
res = TwoSumHashTable(nums, target);
Console.WriteLine("Method 2 res = " + string.Join(",", res));
}
}
@@ -0,0 +1,51 @@
/**
* File: bubble_sort.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_sorting;
public class bubble_sort {
/* Bubble sort */
void BubbleSort(int[] nums) {
// Outer loop: unsorted range is [0, i]
for (int 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 (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
}
}
}
}
/* Bubble sort (flag optimization) */
void BubbleSortWithFlag(int[] nums) {
// Outer loop: unsorted range is [0, i]
for (int i = nums.Length - 1; i > 0; i--) {
bool flag = false; // Initialize flag
// Inner loop: swap the largest element in the unsorted range [0, i] to the rightmost end of that range
for (int j = 0; j < i; j++) {
if (nums[j] > nums[j + 1]) {
// Swap nums[j] and nums[j + 1]
(nums[j + 1], nums[j]) = (nums[j], nums[j + 1]);
flag = true; // Record element swap
}
}
if (!flag) break; // No elements were swapped in this round of "bubbling", exit directly
}
}
[Test]
public void Test() {
int[] nums = [4, 1, 3, 1, 5, 2];
BubbleSort(nums);
Console.WriteLine("After bubble sort, nums = " + string.Join(",", nums));
int[] nums1 = [4, 1, 3, 1, 5, 2];
BubbleSortWithFlag(nums1);
Console.WriteLine("After bubble sort completes, nums1 = " + string.Join(",", nums1));
}
}
@@ -0,0 +1,46 @@
/**
* File: bucket_sort.cs
* Created Time: 2023-04-13
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
public class bucket_sort {
/* Bucket sort */
void BucketSort(float[] nums) {
// Initialize k = n/2 buckets, expected to allocate 2 elements per bucket
int k = nums.Length / 2;
List<List<float>> buckets = [];
for (int i = 0; i < k; i++) {
buckets.Add([]);
}
// 1. Distribute array elements into various buckets
foreach (float num in nums) {
// Input data range is [0, 1), use num * k to map to index range [0, k-1]
int i = (int)(num * k);
// Add num to bucket i
buckets[i].Add(num);
}
// 2. Sort each bucket
foreach (List<float> bucket in buckets) {
// Use built-in sorting function, can also replace with other sorting algorithms
bucket.Sort();
}
// 3. Traverse buckets to merge results
int j = 0;
foreach (List<float> bucket in buckets) {
foreach (float num in bucket) {
nums[j++] = num;
}
}
}
[Test]
public void Test() {
// Assume input data is floating point, interval [0, 1)
float[] nums = [0.49f, 0.96f, 0.82f, 0.09f, 0.57f, 0.43f, 0.91f, 0.75f, 0.15f, 0.37f];
BucketSort(nums);
Console.WriteLine("After bucket sort completes, nums = " + string.Join(" ", nums));
}
}
@@ -0,0 +1,77 @@
/**
* File: counting_sort.cs
* Created Time: 2023-04-13
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
public class counting_sort {
/* Counting sort */
// Simple implementation, cannot be used for sorting objects
void CountingSortNaive(int[] nums) {
// 1. Count the maximum element m in the array
int m = 0;
foreach (int num in nums) {
m = Math.Max(m, num);
}
// 2. Count the occurrence of each number
// counter[num] represents the occurrence of num
int[] counter = new int[m + 1];
foreach (int num in nums) {
counter[num]++;
}
// 3. Traverse counter, filling each element back into the original array nums
int i = 0;
for (int num = 0; num < m + 1; num++) {
for (int j = 0; j < counter[num]; j++, i++) {
nums[i] = num;
}
}
}
/* Counting sort */
// Complete implementation, can sort objects and is a stable sort
void CountingSort(int[] nums) {
// 1. Count the maximum element m in the array
int m = 0;
foreach (int num in nums) {
m = Math.Max(m, num);
}
// 2. Count the occurrence of each number
// counter[num] represents the occurrence of num
int[] counter = new int[m + 1];
foreach (int num in 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 (int 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
int n = nums.Length;
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int 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 (int i = 0; i < n; i++) {
nums[i] = res[i];
}
}
[Test]
public void Test() {
int[] nums = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
CountingSortNaive(nums);
Console.WriteLine("After counting sort (cannot sort objects) completes, nums = " + string.Join(" ", nums));
int[] nums1 = [1, 0, 1, 2, 0, 4, 0, 2, 2, 4];
CountingSort(nums1);
Console.WriteLine("After counting sort completes, nums1 = " + string.Join(" ", nums));
}
}
@@ -0,0 +1,52 @@
/**
* File: heap_sort.cs
* Created Time: 2023-06-01
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
public class heap_sort {
/* Heap length is n, start heapifying node i, from top to bottom */
void SiftDown(int[] nums, int n, int i) {
while (true) {
// If node i is largest or indices l, r are out of bounds, no need to continue heapify, break
int l = 2 * i + 1;
int r = 2 * i + 2;
int 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[ma], nums[i]) = (nums[i], nums[ma]);
// Loop downwards heapification
i = ma;
}
}
/* Heap sort */
void HeapSort(int[] nums) {
// Build heap operation: heapify all nodes except leaves
for (int i = 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 (int i = nums.Length - 1; i > 0; i--) {
// Delete node
(nums[i], nums[0]) = (nums[0], nums[i]);
// Start heapifying the root node, from top to bottom
SiftDown(nums, i, 0);
}
}
[Test]
public void Test() {
int[] nums = [4, 1, 3, 1, 5, 2];
HeapSort(nums);
Console.WriteLine("After heap sort completes, nums = " + string.Join(" ", nums));
}
}
@@ -0,0 +1,30 @@
/**
* File: insertion_sort.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_sorting;
public class insertion_sort {
/* Insertion sort */
void InsertionSort(int[] nums) {
// Outer loop: sorted interval is [0, i-1]
for (int i = 1; i < nums.Length; i++) {
int bas = nums[i], j = i - 1;
// Inner loop: insert base into the correct position within the sorted interval [0, i-1]
while (j >= 0 && nums[j] > bas) {
nums[j + 1] = nums[j]; // Move nums[j] to the right by one position
j--;
}
nums[j + 1] = bas; // Assign base to the correct position
}
}
[Test]
public void Test() {
int[] nums = [4, 1, 3, 1, 5, 2];
InsertionSort(nums);
Console.WriteLine("After insertion sort completes, nums = " + string.Join(",", nums));
}
}
@@ -0,0 +1,56 @@
/**
* File: merge_sort.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_sorting;
public class merge_sort {
/* Merge left subarray and right subarray */
void Merge(int[] nums, int left, int mid, int right) {
// Left subarray interval is [left, mid], right subarray interval is [mid+1, right]
// Create a temporary array tmp to store the merged results
int[] tmp = new int[right - left + 1];
// Initialize the start indices of the left and right subarrays
int 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 */
void MergeSort(int[] nums, int left, int right) {
// Termination condition
if (left >= right) return; // Terminate recursion when subarray length is 1
// Divide and conquer stage
int mid = 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);
}
[Test]
public void Test() {
/* Merge sort */
int[] nums = [7, 3, 2, 6, 0, 1, 5, 4];
MergeSort(nums, 0, nums.Length - 1);
Console.WriteLine("After merge sort completes, nums = " + string.Join(",", nums));
}
}
@@ -0,0 +1,150 @@
/**
* File: quick_sort.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_sorting;
class quickSort {
/* Swap elements */
static void Swap(int[] nums, int i, int j) {
(nums[j], nums[i]) = (nums[i], nums[j]);
}
/* Sentinel partition */
static int Partition(int[] nums, int left, int right) {
// Use nums[left] as the pivot
int 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
Swap(nums, i, j); // Swap these two elements
}
Swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
}
/* Quick sort */
public static void QuickSort(int[] nums, int left, int right) {
// Terminate recursion when subarray length is 1
if (left >= right)
return;
// Sentinel partition
int pivot = Partition(nums, left, right);
// Recursively process the left subarray and right subarray
QuickSort(nums, left, pivot - 1);
QuickSort(nums, pivot + 1, right);
}
}
/* Quick sort class (median pivot optimization) */
class QuickSortMedian {
/* Swap elements */
static void Swap(int[] nums, int i, int j) {
(nums[j], nums[i]) = (nums[i], nums[j]);
}
/* Select the median of three candidate elements */
static int MedianThree(int[] nums, int left, int mid, int right) {
int l = nums[left], m = nums[mid], r = nums[right];
if ((l <= m && m <= r) || (r <= m && m <= l))
return mid; // m is between l and r
if ((m <= l && l <= r) || (r <= l && l <= m))
return left; // l is between m and r
return right;
}
/* Sentinel partition (median of three) */
static int Partition(int[] nums, int left, int right) {
// Select the median of three candidate elements
int med = MedianThree(nums, left, (left + right) / 2, right);
// Swap the median to the array's leftmost position
Swap(nums, left, med);
// Use nums[left] as the pivot
int 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
Swap(nums, i, j); // Swap these two elements
}
Swap(nums, i, left); // Swap the pivot to the boundary between the two subarrays
return i; // Return the index of the pivot
}
/* Quick sort */
public static void QuickSort(int[] nums, int left, int right) {
// Terminate recursion when subarray length is 1
if (left >= right)
return;
// Sentinel partition
int pivot = Partition(nums, left, right);
// Recursively process the left subarray and right subarray
QuickSort(nums, left, pivot - 1);
QuickSort(nums, pivot + 1, right);
}
}
/* Quick sort class (recursion depth optimization) */
class QuickSortTailCall {
/* Swap elements */
static void Swap(int[] nums, int i, int j) {
(nums[j], nums[i]) = (nums[i], nums[j]);
}
/* Sentinel partition */
static int Partition(int[] nums, int left, int right) {
// Use nums[left] as the pivot
int 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
Swap(nums, i, j); // Swap these two elements
}
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) */
public static void QuickSort(int[] nums, int left, int right) {
// Terminate when subarray length is 1
while (left < right) {
// Sentinel partition operation
int pivot = Partition(nums, left, right);
// Perform quick sort on the shorter of the two subarrays
if (pivot - left < right - pivot) {
QuickSort(nums, left, pivot - 1); // Recursively sort the left subarray
left = pivot + 1; // Remaining unsorted interval is [pivot + 1, right]
} else {
QuickSort(nums, pivot + 1, right); // Recursively sort the right subarray
right = pivot - 1; // Remaining unsorted interval is [left, pivot - 1]
}
}
}
}
public class quick_sort {
[Test]
public void Test() {
/* Quick sort */
int[] nums = [2, 4, 1, 0, 3, 5];
quickSort.QuickSort(nums, 0, nums.Length - 1);
Console.WriteLine("After quick sort completes, nums = " + string.Join(",", nums));
/* Quick sort (recursion depth optimization) */
int[] nums1 = [2, 4, 1, 0, 3, 5];
QuickSortMedian.QuickSort(nums1, 0, nums1.Length - 1);
Console.WriteLine("After quick sort (median pivot optimization) completes, nums1 = " + string.Join(",", nums1));
/* Quick sort (recursion depth optimization) */
int[] nums2 = [2, 4, 1, 0, 3, 5];
QuickSortTailCall.QuickSort(nums2, 0, nums2.Length - 1);
Console.WriteLine("After quick sort (recursion depth optimization) completes, nums2 = " + string.Join(",", nums2));
}
}
@@ -0,0 +1,69 @@
/**
* File: radix_sort.cs
* Created Time: 2023-04-13
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
public class radix_sort {
/* Get the k-th digit of element num, where exp = 10^(k-1) */
int Digit(int num, int exp) {
// Passing exp instead of k can avoid repeated expensive exponentiation here
return (num / exp) % 10;
}
/* Counting sort (based on nums k-th digit) */
void CountingSortDigit(int[] nums, int exp) {
// Decimal digit range is 0~9, therefore need a bucket array of length 10
int[] counter = new int[10];
int n = nums.Length;
// Count the occurrence of digits 0~9
for (int i = 0; i < n; i++) {
int 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 (int i = 1; i < 10; i++) {
counter[i] += counter[i - 1];
}
// Traverse in reverse, based on bucket statistics, place each element into res
int[] res = new int[n];
for (int i = n - 1; i >= 0; i--) {
int d = Digit(nums[i], exp);
int 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 (int i = 0; i < n; i++) {
nums[i] = res[i];
}
}
/* Radix sort */
void RadixSort(int[] nums) {
// Get the maximum element of the array, used to determine the maximum number of digits
int m = int.MinValue;
foreach (int num in nums) {
if (num > m) m = num;
}
// Traverse from the lowest to the highest digit
for (int 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);
}
}
[Test]
public void Test() {
// Radix sort
int[] nums = [ 10546151, 35663510, 42865989, 34862445, 81883077,
88906420, 72429244, 30524779, 82060337, 63832996 ];
RadixSort(nums);
Console.WriteLine("After radix sort completes, nums = " + string.Join(" ", nums));
}
}
@@ -0,0 +1,32 @@
/**
* File: selection_sort.cs
* Created Time: 2023-06-01
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_sorting;
public class selection_sort {
/* Selection sort */
void SelectionSort(int[] nums) {
int n = nums.Length;
// Outer loop: unsorted interval is [i, n-1]
for (int i = 0; i < n - 1; i++) {
// Inner loop: find the smallest element within the unsorted interval
int k = i;
for (int 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[k], nums[i]) = (nums[i], nums[k]);
}
}
[Test]
public void Test() {
int[] nums = [4, 1, 3, 1, 5, 2];
SelectionSort(nums);
Console.WriteLine("After selection sort completes, nums = " + string.Join(" ", nums));
}
}
@@ -0,0 +1,152 @@
/**
* File: array_deque.cs
* Created Time: 2023-03-08
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Double-ended queue based on circular array implementation */
public class ArrayDeque {
int[] nums; // Array for storing double-ended queue elements
int front; // Front pointer, points to the front of the queue element
int queSize; // Double-ended queue length
/* Constructor */
public ArrayDeque(int capacity) {
nums = new int[capacity];
front = queSize = 0;
}
/* Get the capacity of the double-ended queue */
int Capacity() {
return nums.Length;
}
/* Get the length of the double-ended queue */
public int Size() {
return queSize;
}
/* Check if the double-ended queue is empty */
public bool IsEmpty() {
return queSize == 0;
}
/* Calculate circular array index */
int Index(int i) {
// 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 + Capacity()) % Capacity();
}
/* Front of the queue enqueue */
public void PushFirst(int num) {
if (queSize == Capacity()) {
Console.WriteLine("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
front = Index(front - 1);
// Add num to front of queue
nums[front] = num;
queSize++;
}
/* Rear of the queue enqueue */
public void PushLast(int num) {
if (queSize == Capacity()) {
Console.WriteLine("Double-ended queue is full");
return;
}
// Use modulo operation to wrap rear around to the head after passing the tail of the array
int rear = Index(front + queSize);
// Front pointer moves one position backward
nums[rear] = num;
queSize++;
}
/* Rear of the queue dequeue */
public int PopFirst() {
int num = PeekFirst();
// Move front pointer backward by one position
front = Index(front + 1);
queSize--;
return num;
}
/* Access rear of the queue element */
public int PopLast() {
int num = PeekLast();
queSize--;
return num;
}
/* Return list for printing */
public int PeekFirst() {
if (IsEmpty()) {
throw new InvalidOperationException();
}
return nums[front];
}
/* Driver Code */
public int PeekLast() {
if (IsEmpty()) {
throw new InvalidOperationException();
}
// Initialize double-ended queue
int last = Index(front + queSize - 1);
return nums[last];
}
/* Return array for printing */
public int[] ToArray() {
// Elements enqueue
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[Index(j)];
}
return res;
}
}
public class array_deque {
[Test]
public void Test() {
/* Get the length of the double-ended queue */
ArrayDeque deque = new(10);
deque.PushLast(3);
deque.PushLast(2);
deque.PushLast(5);
Console.WriteLine("Double-ended queue deque = " + string.Join(" ", deque.ToArray()));
/* Update element */
int peekFirst = deque.PeekFirst();
Console.WriteLine("Front element peekFirst = " + peekFirst);
int peekLast = deque.PeekLast();
Console.WriteLine("Rear element peekLast = " + peekLast);
/* Elements enqueue */
deque.PushLast(4);
Console.WriteLine("After element 4 enqueues at rear, deque = " + string.Join(" ", deque.ToArray()));
deque.PushFirst(1);
Console.WriteLine("After element 1 enqueues at front, deque = " + string.Join(" ", deque.ToArray()));
/* Element dequeue */
int popLast = deque.PopLast();
Console.WriteLine("Rear dequeue element = " + popLast + ", after rear dequeue, deque = " + string.Join(" ", deque.ToArray()));
int popFirst = deque.PopFirst();
Console.WriteLine("Front dequeue element = " + popFirst + ", after front dequeue, deque = " + string.Join(" ", deque.ToArray()));
/* Get the length of the double-ended queue */
int size = deque.Size();
Console.WriteLine("Double-ended queue length size = " + size);
/* Check if the double-ended queue is empty */
bool isEmpty = deque.IsEmpty();
Console.WriteLine("Double-ended queue is empty = " + isEmpty);
}
}
@@ -0,0 +1,114 @@
/**
* File: array_queue.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Queue based on circular array implementation */
class ArrayQueue {
int[] nums; // Array for storing queue elements
int front; // Front pointer, points to the front of the queue element
int queSize; // Queue length
public ArrayQueue(int capacity) {
nums = new int[capacity];
front = queSize = 0;
}
/* Get the capacity of the queue */
int Capacity() {
return nums.Length;
}
/* Get the length of the queue */
public int Size() {
return queSize;
}
/* Check if the queue is empty */
public bool IsEmpty() {
return queSize == 0;
}
/* Enqueue */
public void Push(int num) {
if (queSize == Capacity()) {
Console.WriteLine("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
int rear = (front + queSize) % Capacity();
// Front pointer moves one position backward
nums[rear] = num;
queSize++;
}
/* Dequeue */
public int Pop() {
int num = Peek();
// Move front pointer backward by one position, if it passes the tail, return to array head
front = (front + 1) % Capacity();
queSize--;
return num;
}
/* Return list for printing */
public int Peek() {
if (IsEmpty())
throw new Exception();
return nums[front];
}
/* Return array */
public int[] ToArray() {
// Elements enqueue
int[] res = new int[queSize];
for (int i = 0, j = front; i < queSize; i++, j++) {
res[i] = nums[j % this.Capacity()];
}
return res;
}
}
public class array_queue {
[Test]
public void Test() {
/* Access front of the queue element */
int capacity = 10;
ArrayQueue queue = new(capacity);
/* Elements enqueue */
queue.Push(1);
queue.Push(3);
queue.Push(2);
queue.Push(5);
queue.Push(4);
Console.WriteLine("Queue queue = " + string.Join(",", queue.ToArray()));
/* Return list for printing */
int peek = queue.Peek();
Console.WriteLine("Front element peek = " + peek);
/* Element dequeue */
int pop = queue.Pop();
Console.WriteLine("Dequeue element pop = " + pop + ", after dequeue, queue = " + string.Join(",", queue.ToArray()));
/* Get the length of the queue */
int size = queue.Size();
Console.WriteLine("Queue length size = " + size);
/* Check if the queue is empty */
bool isEmpty = queue.IsEmpty();
Console.WriteLine("Queue is empty = " + isEmpty);
/* Test circular array */
for (int i = 0; i < 10; i++) {
queue.Push(i);
queue.Pop();
Console.WriteLine("Round " + i + " enqueue + dequeue, queue = " + string.Join(",", queue.ToArray()));
}
}
}
@@ -0,0 +1,84 @@
/**
* File: array_stack.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Stack based on array implementation */
class ArrayStack {
List<int> stack;
public ArrayStack() {
// Initialize list (dynamic array)
stack = [];
}
/* Get the length of the stack */
public int Size() {
return stack.Count;
}
/* Check if the stack is empty */
public bool IsEmpty() {
return Size() == 0;
}
/* Push */
public void Push(int num) {
stack.Add(num);
}
/* Pop */
public int Pop() {
if (IsEmpty())
throw new Exception();
var val = Peek();
stack.RemoveAt(Size() - 1);
return val;
}
/* Return list for printing */
public int Peek() {
if (IsEmpty())
throw new Exception();
return stack[Size() - 1];
}
/* Convert List to Array and return */
public int[] ToArray() {
return [.. stack];
}
}
public class array_stack {
[Test]
public void Test() {
/* Access top of the stack element */
ArrayStack stack = new();
/* Elements push onto stack */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);
Console.WriteLine("Stack stack = " + string.Join(",", stack.ToArray()));
/* Return list for printing */
int peek = stack.Peek();
Console.WriteLine("Stack top element peek = " + peek);
/* Element pop from stack */
int pop = stack.Pop();
Console.WriteLine("Pop element pop = " + pop + ", after pop, stack = " + string.Join(",", stack.ToArray()));
/* Get the length of the stack */
int size = stack.Size();
Console.WriteLine("Stack length size = " + size);
/* Check if empty */
bool isEmpty = stack.IsEmpty();
Console.WriteLine("Stack is empty = " + isEmpty);
}
}
@@ -0,0 +1,44 @@
/**
* File: deque.cs
* Created Time: 2022-12-30
* Author: moonache (microin1301@outlook.com)
*/
namespace hello_algo.chapter_stack_and_queue;
public class deque {
[Test]
public void Test() {
/* Get the length of the double-ended queue */
// In C#, use LinkedList as deque
LinkedList<int> deque = new();
/* Elements enqueue */
deque.AddLast(2); // Add to the rear of the queue
deque.AddLast(5);
deque.AddLast(4);
deque.AddFirst(3); // Add to the front of the queue
deque.AddFirst(1);
Console.WriteLine("Double-ended queue deque = " + string.Join(",", deque));
/* Update element */
int? peekFirst = deque.First?.Value; // Rear of the queue element
Console.WriteLine("Front element peekFirst = " + peekFirst);
int? peekLast = deque.Last?.Value; // Front of the queue element dequeues
Console.WriteLine("Rear element peekLast = " + peekLast);
/* Element dequeue */
deque.RemoveFirst(); // Check if the double-ended queue is empty
Console.WriteLine("After front element dequeues, deque = " + string.Join(",", deque));
deque.RemoveLast(); // Rear element dequeue
Console.WriteLine("After rear element dequeues, deque = " + string.Join(",", deque));
/* Get the length of the double-ended queue */
int size = deque.Count;
Console.WriteLine("Double-ended queue length size = " + size);
/* Check if the double-ended queue is empty */
bool isEmpty = deque.Count == 0;
Console.WriteLine("Double-ended queue is empty = " + isEmpty);
}
}
@@ -0,0 +1,177 @@
/**
* File: linkedlist_deque.cs
* Created Time: 2023-03-08
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Doubly linked list node */
public class ListNode(int val) {
public int val = val; // Node value
public ListNode? next = null; // Successor node reference
public ListNode? prev = null; // Predecessor node reference
}
/* Double-ended queue based on doubly linked list implementation */
public class LinkedListDeque {
ListNode? front, rear; // Head node front, tail node rear
int queSize = 0; // Length of the double-ended queue
public LinkedListDeque() {
front = null;
rear = null;
}
/* Get the length of the double-ended queue */
public int Size() {
return queSize;
}
/* Check if the double-ended queue is empty */
public bool IsEmpty() {
return Size() == 0;
}
/* Enqueue operation */
void Push(int num, bool isFront) {
ListNode node = new(num);
// If the linked list is empty, make both front and rear point to node
if (IsEmpty()) {
front = node;
rear = node;
}
// Front of the queue enqueue operation
else if (isFront) {
// Add node to the head of the linked list
front!.prev = node;
node.next = front;
front = node; // Update head node
}
// Rear of the queue enqueue operation
else {
// Add node to the tail of the linked list
rear!.next = node;
node.prev = rear;
rear = node; // Update tail node
}
queSize++; // Update queue length
}
/* Front of the queue enqueue */
public void PushFirst(int num) {
Push(num, true);
}
/* Rear of the queue enqueue */
public void PushLast(int num) {
Push(num, false);
}
/* Dequeue operation */
int? Pop(bool isFront) {
if (IsEmpty())
throw new Exception();
int? val;
// Temporarily store head node value
if (isFront) {
val = front?.val; // Delete head node
// Delete head node
ListNode? fNext = front?.next;
if (fNext != null) {
fNext.prev = null;
front!.next = null;
}
front = fNext; // Update head node
}
// Temporarily store tail node value
else {
val = rear?.val; // Delete tail node
// Update tail node
ListNode? rPrev = rear?.prev;
if (rPrev != null) {
rPrev.next = null;
rear!.prev = null;
}
rear = rPrev; // Update tail node
}
queSize--; // Update queue length
return val;
}
/* Rear of the queue dequeue */
public int? PopFirst() {
return Pop(true);
}
/* Access rear of the queue element */
public int? PopLast() {
return Pop(false);
}
/* Return list for printing */
public int? PeekFirst() {
if (IsEmpty())
throw new Exception();
return front?.val;
}
/* Driver Code */
public int? PeekLast() {
if (IsEmpty())
throw new Exception();
return rear?.val;
}
/* Return array for printing */
public int?[] ToArray() {
ListNode? node = front;
int?[] res = new int?[Size()];
for (int i = 0; i < res.Length; i++) {
res[i] = node?.val;
node = node?.next;
}
return res;
}
}
public class linkedlist_deque {
[Test]
public void Test() {
/* Get the length of the double-ended queue */
LinkedListDeque deque = new();
deque.PushLast(3);
deque.PushLast(2);
deque.PushLast(5);
Console.WriteLine("Double-ended queue deque = " + string.Join(" ", deque.ToArray()));
/* Update element */
int? peekFirst = deque.PeekFirst();
Console.WriteLine("Front element peekFirst = " + peekFirst);
int? peekLast = deque.PeekLast();
Console.WriteLine("Rear element peekLast = " + peekLast);
/* Elements enqueue */
deque.PushLast(4);
Console.WriteLine("After element 4 enqueues at rear, deque = " + string.Join(" ", deque.ToArray()));
deque.PushFirst(1);
Console.WriteLine("After element 1 enqueues at front, deque = " + string.Join(" ", deque.ToArray()));
/* Element dequeue */
int? popLast = deque.PopLast();
Console.WriteLine("Rear dequeue element = " + popLast + ", after rear dequeue, deque = " + string.Join(" ", deque.ToArray()));
int? popFirst = deque.PopFirst();
Console.WriteLine("Front dequeue element = " + popFirst + ", after front dequeue, deque = " + string.Join(" ", deque.ToArray()));
/* Get the length of the double-ended queue */
int size = deque.Size();
Console.WriteLine("Double-ended queue length size = " + size);
/* Check if the double-ended queue is empty */
bool isEmpty = deque.IsEmpty();
Console.WriteLine("Double-ended queue is empty = " + isEmpty);
}
}
@@ -0,0 +1,106 @@
/**
* File: linkedlist_queue.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Queue based on linked list implementation */
class LinkedListQueue {
ListNode? front, rear; // Head node front, tail node rear
int queSize = 0;
public LinkedListQueue() {
front = null;
rear = null;
}
/* Get the length of the queue */
public int Size() {
return queSize;
}
/* Check if the queue is empty */
public bool IsEmpty() {
return Size() == 0;
}
/* Enqueue */
public void Push(int num) {
// Add num after the tail node
ListNode node = new(num);
// If the queue is empty, make both front and rear point to the node
if (front == null) {
front = node;
rear = node;
// If the queue is not empty, add the node after the tail node
} else if (rear != null) {
rear.next = node;
rear = node;
}
queSize++;
}
/* Dequeue */
public int Pop() {
int num = Peek();
// Delete head node
front = front?.next;
queSize--;
return num;
}
/* Return list for printing */
public int Peek() {
if (IsEmpty())
throw new Exception();
return front!.val;
}
/* Convert linked list to Array and return */
public int[] ToArray() {
if (front == null)
return [];
ListNode? node = front;
int[] res = new int[Size()];
for (int i = 0; i < res.Length; i++) {
res[i] = node!.val;
node = node.next;
}
return res;
}
}
public class linkedlist_queue {
[Test]
public void Test() {
/* Access front of the queue element */
LinkedListQueue queue = new();
/* Elements enqueue */
queue.Push(1);
queue.Push(3);
queue.Push(2);
queue.Push(5);
queue.Push(4);
Console.WriteLine("Queue queue = " + string.Join(",", queue.ToArray()));
/* Return list for printing */
int peek = queue.Peek();
Console.WriteLine("Front element peek = " + peek);
/* Element dequeue */
int pop = queue.Pop();
Console.WriteLine("Dequeue element pop = " + pop + ", after dequeue, queue = " + string.Join(",", queue.ToArray()));
/* Get the length of the queue */
int size = queue.Size();
Console.WriteLine("Queue length size = " + size);
/* Check if the queue is empty */
bool isEmpty = queue.IsEmpty();
Console.WriteLine("Queue is empty = " + isEmpty);
}
}
@@ -0,0 +1,97 @@
/**
* File: linkedlist_stack.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
/* Stack based on linked list implementation */
class LinkedListStack {
ListNode? stackPeek; // Use head node as stack top
int stkSize = 0; // Stack length
public LinkedListStack() {
stackPeek = null;
}
/* Get the length of the stack */
public int Size() {
return stkSize;
}
/* Check if the stack is empty */
public bool IsEmpty() {
return Size() == 0;
}
/* Push */
public void Push(int num) {
ListNode node = new(num) {
next = stackPeek
};
stackPeek = node;
stkSize++;
}
/* Pop */
public int Pop() {
int num = Peek();
stackPeek = stackPeek!.next;
stkSize--;
return num;
}
/* Return list for printing */
public int Peek() {
if (IsEmpty())
throw new Exception();
return stackPeek!.val;
}
/* Convert List to Array and return */
public int[] ToArray() {
if (stackPeek == null)
return [];
ListNode? node = stackPeek;
int[] res = new int[Size()];
for (int i = res.Length - 1; i >= 0; i--) {
res[i] = node!.val;
node = node.next;
}
return res;
}
}
public class linkedlist_stack {
[Test]
public void Test() {
/* Access top of the stack element */
LinkedListStack stack = new();
/* Elements push onto stack */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);
Console.WriteLine("Stack stack = " + string.Join(",", stack.ToArray()));
/* Return list for printing */
int peek = stack.Peek();
Console.WriteLine("Stack top element peek = " + peek);
/* Element pop from stack */
int pop = stack.Pop();
Console.WriteLine("Pop element pop = " + pop + ", after pop, stack = " + string.Join(",", stack.ToArray()));
/* Get the length of the stack */
int size = stack.Size();
Console.WriteLine("Stack length size = " + size);
/* Check if empty */
bool isEmpty = stack.IsEmpty();
Console.WriteLine("Stack is empty = " + isEmpty);
}
}
@@ -0,0 +1,39 @@
/**
* File: queue.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
public class queue {
[Test]
public void Test() {
/* Access front of the queue element */
Queue<int> queue = new();
/* Elements enqueue */
queue.Enqueue(1);
queue.Enqueue(3);
queue.Enqueue(2);
queue.Enqueue(5);
queue.Enqueue(4);
Console.WriteLine("Queue queue = " + string.Join(",", queue));
/* Return list for printing */
int peek = queue.Peek();
Console.WriteLine("Front element peek = " + peek);
/* Element dequeue */
int pop = queue.Dequeue();
Console.WriteLine("Dequeue element pop = " + pop + ", after dequeue, queue = " + string.Join(",", queue));
/* Get the length of the queue */
int size = queue.Count;
Console.WriteLine("Queue length size = " + size);
/* Check if the queue is empty */
bool isEmpty = queue.Count == 0;
Console.WriteLine("Queue is empty = " + isEmpty);
}
}
@@ -0,0 +1,40 @@
/**
* File: stack.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_stack_and_queue;
public class stack {
[Test]
public void Test() {
/* Access top of the stack element */
Stack<int> stack = new();
/* Elements push onto stack */
stack.Push(1);
stack.Push(3);
stack.Push(2);
stack.Push(5);
stack.Push(4);
// Note: stack.ToArray() returns reversed sequence, index 0 is stack top
Console.WriteLine("Stack stack = " + string.Join(",", stack));
/* Return list for printing */
int peek = stack.Peek();
Console.WriteLine("Stack top element peek = " + peek);
/* Element pop from stack */
int pop = stack.Pop();
Console.WriteLine("Pop element pop = " + pop + ", after pop, stack = " + string.Join(",", stack));
/* Get the length of the stack */
int size = stack.Count;
Console.WriteLine("Stack length size = " + size);
/* Check if empty */
bool isEmpty = stack.Count == 0;
Console.WriteLine("Stack is empty = " + isEmpty);
}
}
@@ -0,0 +1,129 @@
/**
* File: array_binary_tree.cs
* Created Time: 2023-07-20
* Author: hpstory (hpstory1024@163.com)
*/
namespace hello_algo.chapter_tree;
/* Binary tree class represented by array */
public class ArrayBinaryTree(List<int?> arr) {
List<int?> tree = new(arr);
/* List capacity */
public int Size() {
return tree.Count;
}
/* Get value of node at index i */
public int? Val(int i) {
// If index out of bounds, return null to represent empty position
if (i < 0 || i >= Size())
return null;
return tree[i];
}
/* Get index of left child node of node at index i */
public int Left(int i) {
return 2 * i + 1;
}
/* Get index of right child node of node at index i */
public int Right(int i) {
return 2 * i + 2;
}
/* Get index of parent node of node at index i */
public int Parent(int i) {
return (i - 1) / 2;
}
/* Level-order traversal */
public List<int> LevelOrder() {
List<int> res = [];
// Traverse array directly
for (int i = 0; i < Size(); i++) {
if (Val(i).HasValue)
res.Add(Val(i)!.Value);
}
return res;
}
/* Depth-first traversal */
void DFS(int i, string order, List<int> res) {
// If empty position, return
if (!Val(i).HasValue)
return;
// Preorder traversal
if (order == "pre")
res.Add(Val(i)!.Value);
DFS(Left(i), order, res);
// Inorder traversal
if (order == "in")
res.Add(Val(i)!.Value);
DFS(Right(i), order, res);
// Postorder traversal
if (order == "post")
res.Add(Val(i)!.Value);
}
/* Preorder traversal */
public List<int> PreOrder() {
List<int> res = [];
DFS(0, "pre", res);
return res;
}
/* Inorder traversal */
public List<int> InOrder() {
List<int> res = [];
DFS(0, "in", res);
return res;
}
/* Postorder traversal */
public List<int> PostOrder() {
List<int> res = [];
DFS(0, "post", res);
return res;
}
}
public class array_binary_tree {
[Test]
public void Test() {
// Initialize binary tree
// Here we use a function to generate a binary tree directly from an array
List<int?> arr = [1, 2, 3, 4, null, 6, 7, 8, 9, null, null, 12, null, null, 15];
TreeNode? root = TreeNode.ListToTree(arr);
Console.WriteLine("\nInitialize binary tree\n");
Console.WriteLine("Array representation of binary tree:");
Console.WriteLine(arr.PrintList());
Console.WriteLine("Linked list representation of binary tree:");
PrintUtil.PrintTree(root);
// Binary tree class represented by array
ArrayBinaryTree abt = new(arr);
// Access node
int i = 1;
int l = abt.Left(i);
int r = abt.Right(i);
int p = abt.Parent(i);
Console.WriteLine("\nCurrent node index is " + i + ", value is " + abt.Val(i));
Console.WriteLine("Its left child node index is " + l + ", value is " + (abt.Val(l).HasValue ? abt.Val(l) : "null"));
Console.WriteLine("Its right child node index is " + r + ", value is " + (abt.Val(r).HasValue ? abt.Val(r) : "null"));
Console.WriteLine("Its parent node index is " + p + ", value is " + (abt.Val(p).HasValue ? abt.Val(p) : "null"));
// Traverse tree
List<int> res = abt.LevelOrder();
Console.WriteLine("\nLevel-order traversal is:" + res.PrintList());
res = abt.PreOrder();
Console.WriteLine("Preorder traversal is:" + res.PrintList());
res = abt.InOrder();
Console.WriteLine("Inorder traversal is:" + res.PrintList());
res = abt.PostOrder();
Console.WriteLine("Postorder traversal is:" + res.PrintList());
}
}
+216
View File
@@ -0,0 +1,216 @@
/**
* File: avl_tree.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_tree;
/* AVL tree */
class AVLTree {
public TreeNode? root; // Root node
/* Get node height */
int Height(TreeNode? node) {
// Empty node height is -1, leaf node height is 0
return node == null ? -1 : node.height;
}
/* Update node height */
void UpdateHeight(TreeNode node) {
// Node height equals the height of the tallest subtree + 1
node.height = Math.Max(Height(node.left), Height(node.right)) + 1;
}
/* Get balance factor */
public int BalanceFactor(TreeNode? node) {
// Empty node balance factor is 0
if (node == null) return 0;
// Node balance factor = left subtree height - right subtree height
return Height(node.left) - Height(node.right);
}
/* Right rotation operation */
TreeNode? RightRotate(TreeNode? node) {
TreeNode? child = node?.left;
TreeNode? grandChild = child?.right;
// Using child as pivot, rotate node to the right
child.right = node;
node.left = grandChild;
// Update node height
UpdateHeight(node);
UpdateHeight(child);
// Return root node of subtree after rotation
return child;
}
/* Left rotation operation */
TreeNode? LeftRotate(TreeNode? node) {
TreeNode? child = node?.right;
TreeNode? grandChild = child?.left;
// Using child as pivot, rotate node to the left
child.left = node;
node.right = grandChild;
// Update node height
UpdateHeight(node);
UpdateHeight(child);
// Return root node of subtree after rotation
return child;
}
/* Perform rotation operation to restore balance to this subtree */
TreeNode? Rotate(TreeNode? node) {
// Get balance factor of node
int balanceFactorInt = BalanceFactor(node);
// Left-leaning tree
if (balanceFactorInt > 1) {
if (BalanceFactor(node?.left) >= 0) {
// Right rotation
return RightRotate(node);
} else {
// First left rotation then right rotation
node!.left = LeftRotate(node!.left);
return RightRotate(node);
}
}
// Right-leaning tree
if (balanceFactorInt < -1) {
if (BalanceFactor(node?.right) <= 0) {
// Left rotation
return LeftRotate(node);
} else {
// First right rotation then left rotation
node!.right = RightRotate(node!.right);
return LeftRotate(node);
}
}
// Balanced tree, no rotation needed, return directly
return node;
}
/* Insert node */
public void Insert(int val) {
root = InsertHelper(root, val);
}
/* Recursively insert node (helper method) */
TreeNode? InsertHelper(TreeNode? node, int val) {
if (node == null) return new TreeNode(val);
/* 1. Find insertion position and insert node */
if (val < node.val)
node.left = InsertHelper(node.left, val);
else if (val > node.val)
node.right = InsertHelper(node.right, val);
else
return node; // Duplicate node not inserted, return directly
UpdateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
node = Rotate(node);
// Return root node of subtree
return node;
}
/* Remove node */
public void Remove(int val) {
root = RemoveHelper(root, val);
}
/* Recursively delete node (helper method) */
TreeNode? RemoveHelper(TreeNode? node, int val) {
if (node == null) return null;
/* 1. Find node and delete */
if (val < node.val)
node.left = RemoveHelper(node.left, val);
else if (val > node.val)
node.right = RemoveHelper(node.right, val);
else {
if (node.left == null || node.right == null) {
TreeNode? child = node.left ?? node.right;
// Number of child nodes = 0, delete node directly and return
if (child == null)
return null;
// Number of child nodes = 1, delete node directly
else
node = child;
} else {
// Number of child nodes = 2, delete the next node in inorder traversal and replace current node with it
TreeNode? temp = node.right;
while (temp.left != null) {
temp = temp.left;
}
node.right = RemoveHelper(node.right, temp.val!.Value);
node.val = temp.val;
}
}
UpdateHeight(node); // Update node height
/* 2. Perform rotation operation to restore balance to this subtree */
node = Rotate(node);
// Return root node of subtree
return node;
}
/* Search node */
public TreeNode? Search(int val) {
TreeNode? cur = root;
// Loop search, exit after passing leaf node
while (cur != null) {
// Target node is in cur's right subtree
if (cur.val < val)
cur = cur.right;
// Target node is in cur's left subtree
else if (cur.val > val)
cur = cur.left;
// Found target node, exit loop
else
break;
}
// Return target node
return cur;
}
}
public class avl_tree {
static void TestInsert(AVLTree tree, int val) {
tree.Insert(val);
Console.WriteLine("\nInsert node " + val + ", AVL tree is");
PrintUtil.PrintTree(tree.root);
}
static void TestRemove(AVLTree tree, int val) {
tree.Remove(val);
Console.WriteLine("\nRemove node " + val + ", AVL tree is");
PrintUtil.PrintTree(tree.root);
}
[Test]
public void Test() {
/* Please pay attention to how the AVL tree maintains balance after inserting nodes */
AVLTree avlTree = new();
/* 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 */
TreeNode? node = avlTree.Search(7);
Console.WriteLine("\nFound node object is " + node + ", node value = " + node?.val);
}
}
@@ -0,0 +1,160 @@
/**
* File: binary_search_tree.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_tree;
class BinarySearchTree {
TreeNode? root;
public BinarySearchTree() {
// Initialize empty tree
root = null;
}
/* Get binary tree root node */
public TreeNode? GetRoot() {
return root;
}
/* Search node */
public TreeNode? Search(int num) {
TreeNode? cur = 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 */
public void Insert(int num) {
// If tree is empty, initialize root node
if (root == null) {
root = new TreeNode(num);
return;
}
TreeNode? cur = root, pre = 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
TreeNode node = new(num);
if (pre != null) {
if (pre.val < num)
pre.right = node;
else
pre.left = node;
}
}
/* Remove node */
public void Remove(int num) {
// If tree is empty, return directly
if (root == null)
return;
TreeNode? cur = root, pre = 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
TreeNode? child = cur.left ?? cur.right;
// Delete node cur
if (cur != root) {
if (pre!.left == cur)
pre.left = child;
else
pre.right = child;
} else {
// If deleted node is root node, reassign root node
root = child;
}
}
// Number of child nodes = 2
else {
// Get next node of cur in inorder traversal
TreeNode? tmp = cur.right;
while (tmp.left != null) {
tmp = tmp.left;
}
// Recursively delete node tmp
Remove(tmp.val!.Value);
// Replace cur with tmp
cur.val = tmp.val;
}
}
}
public class binary_search_tree {
[Test]
public void Test() {
/* Initialize binary search tree */
BinarySearchTree bst = new();
// Please note that different insertion orders will generate different binary trees, this sequence can generate a perfect binary tree
int[] nums = [8, 4, 12, 2, 6, 10, 14, 1, 3, 5, 7, 9, 11, 13, 15];
foreach (int num in nums) {
bst.Insert(num);
}
Console.WriteLine("\nInitialized binary tree is\n");
PrintUtil.PrintTree(bst.GetRoot());
/* Search node */
TreeNode? node = bst.Search(7);
Console.WriteLine("\nFound node object is " + node + ", node value = " + node?.val);
/* Insert node */
bst.Insert(16);
Console.WriteLine("\nAfter inserting node 16, binary tree is\n");
PrintUtil.PrintTree(bst.GetRoot());
/* Remove node */
bst.Remove(1);
Console.WriteLine("\nAfter removing node 1, binary tree is\n");
PrintUtil.PrintTree(bst.GetRoot());
bst.Remove(2);
Console.WriteLine("\nAfter removing node 2, binary tree is\n");
PrintUtil.PrintTree(bst.GetRoot());
bst.Remove(4);
Console.WriteLine("\nAfter removing node 4, binary tree is\n");
PrintUtil.PrintTree(bst.GetRoot());
}
}
@@ -0,0 +1,39 @@
/**
* File: binary_tree.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_tree;
public class binary_tree {
[Test]
public void Test() {
/* Initialize binary tree */
// Initialize nodes
TreeNode n1 = new(1);
TreeNode n2 = new(2);
TreeNode n3 = new(3);
TreeNode n4 = new(4);
TreeNode n5 = new(5);
// Build references (pointers) between nodes
n1.left = n2;
n1.right = n3;
n2.left = n4;
n2.right = n5;
Console.WriteLine("\nInitialize binary tree\n");
PrintUtil.PrintTree(n1);
/* Insert node P between n1 -> n2 */
TreeNode P = new(0);
// Delete node
n1.left = P;
P.left = n2;
Console.WriteLine("\nAfter inserting node P\n");
PrintUtil.PrintTree(n1);
// Remove node P
n1.left = n2;
Console.WriteLine("\nAfter removing node P\n");
PrintUtil.PrintTree(n1);
}
}
@@ -0,0 +1,40 @@
/**
* File: binary_tree_bfs.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_tree;
public class binary_tree_bfs {
/* Level-order traversal */
List<int> LevelOrder(TreeNode root) {
// Initialize queue, add root node
Queue<TreeNode> queue = new();
queue.Enqueue(root);
// Initialize a list to save the traversal sequence
List<int> list = [];
while (queue.Count != 0) {
TreeNode node = queue.Dequeue(); // Dequeue
list.Add(node.val!.Value); // Save node value
if (node.left != null)
queue.Enqueue(node.left); // Left child node enqueue
if (node.right != null)
queue.Enqueue(node.right); // Right child node enqueue
}
return list;
}
[Test]
public void Test() {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree\n");
PrintUtil.PrintTree(root);
List<int> list = LevelOrder(root!);
Console.WriteLine("\nLevel-order traversal node print sequence = " + string.Join(",", list));
}
}
@@ -0,0 +1,59 @@
/**
* File: binary_tree_dfs.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.chapter_tree;
public class binary_tree_dfs {
List<int> list = [];
/* Preorder traversal */
void PreOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: root node -> left subtree -> right subtree
list.Add(root.val!.Value);
PreOrder(root.left);
PreOrder(root.right);
}
/* Inorder traversal */
void InOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: left subtree -> root node -> right subtree
InOrder(root.left);
list.Add(root.val!.Value);
InOrder(root.right);
}
/* Postorder traversal */
void PostOrder(TreeNode? root) {
if (root == null) return;
// Visit priority: left subtree -> right subtree -> root node
PostOrder(root.left);
PostOrder(root.right);
list.Add(root.val!.Value);
}
[Test]
public void Test() {
/* Initialize binary tree */
// Here we use a function to generate a binary tree directly from an array
TreeNode? root = TreeNode.ListToTree([1, 2, 3, 4, 5, 6, 7]);
Console.WriteLine("\nInitialize binary tree\n");
PrintUtil.PrintTree(root);
list.Clear();
PreOrder(root);
Console.WriteLine("\nPreorder traversal node print sequence = " + string.Join(",", list));
list.Clear();
InOrder(root);
Console.WriteLine("\nInorder traversal node print sequence = " + string.Join(",", list));
list.Clear();
PostOrder(root);
Console.WriteLine("\nPostorder traversal node print sequence = " + string.Join(",", list));
}
}
+25
View File
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.5.002.0
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "hello-algo", "hello-algo.csproj", "{48B60439-EFDC-4C8F-AE8D-41979958C8AC}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{48B60439-EFDC-4C8F-AE8D-41979958C8AC}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {1E773F8A-FF66-4974-820B-FCE9032D19AE}
EndGlobalSection
EndGlobal
+21
View File
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<RootNamespace>hello_algo</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
<PackageReference Include="NUnit" Version="3.14.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project>
+32
View File
@@ -0,0 +1,32 @@
// File: ListNode.cs
// Created Time: 2022-12-16
// Author: mingXta (1195669834@qq.com)
namespace hello_algo.utils;
/* Linked list node */
public class ListNode(int x) {
public int val = x;
public ListNode? next;
/* Deserialize array to linked list */
public static ListNode? ArrToLinkedList(int[] arr) {
ListNode dum = new(0);
ListNode head = dum;
foreach (int val in arr) {
head.next = new ListNode(val);
head = head.next;
}
return dum.next;
}
public override string? ToString() {
List<string> list = [];
var head = this;
while (head != null) {
list.Add(head.val.ToString());
head = head.next;
}
return string.Join("->", list);
}
}
+132
View File
@@ -0,0 +1,132 @@
/**
* File: PrintUtil.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com), krahets (krahets@163.com)
*/
namespace hello_algo.utils;
public class Trunk(Trunk? prev, string str) {
public Trunk? prev = prev;
public string str = str;
};
public static class PrintUtil {
/* Print list */
public static void PrintList<T>(IList<T> list) {
Console.WriteLine("[" + string.Join(", ", list) + "]");
}
public static string PrintList<T>(this IEnumerable<T?> list) {
return $"[ {string.Join(", ", list.Select(x => x?.ToString() ?? "null"))} ]";
}
/* Print matrix (Array) */
public static void PrintMatrix<T>(T[][] matrix) {
Console.WriteLine("[");
foreach (T[] row in matrix) {
Console.WriteLine(" " + string.Join(", ", row) + ",");
}
Console.WriteLine("]");
}
/* Print matrix (List) */
public static void PrintMatrix<T>(List<List<T>> matrix) {
Console.WriteLine("[");
foreach (List<T> row in matrix) {
Console.WriteLine(" " + string.Join(", ", row) + ",");
}
Console.WriteLine("]");
}
/* Print linked list */
public static void PrintLinkedList(ListNode? head) {
List<string> list = [];
while (head != null) {
list.Add(head.val.ToString());
head = head.next;
}
Console.Write(string.Join(" -> ", list));
}
/**
* Print binary tree
* This tree printer is borrowed from TECHIE DELIGHT
* https://www.techiedelight.com/c-program-print-binary-tree/
*/
public static void PrintTree(TreeNode? root) {
PrintTree(root, null, false);
}
/* Print binary tree */
public static void PrintTree(TreeNode? root, Trunk? prev, bool isRight) {
if (root == null) {
return;
}
string prev_str = " ";
Trunk trunk = new(prev, prev_str);
PrintTree(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.WriteLine(" " + root.val);
if (prev != null) {
prev.str = prev_str;
}
trunk.str = " |";
PrintTree(root.left, trunk, false);
}
public static void ShowTrunks(Trunk? p) {
if (p == null) {
return;
}
ShowTrunks(p.prev);
Console.Write(p.str);
}
/* Print hash table */
public static void PrintHashMap<K, V>(Dictionary<K, V> map) where K : notnull {
foreach (var kv in map.Keys) {
Console.WriteLine(kv.ToString() + " -> " + map[kv]?.ToString());
}
}
/* Print heap */
public static void PrintHeap(Queue<int> queue) {
Console.Write("Heap array representation:");
List<int> list = [.. queue];
Console.WriteLine(string.Join(',', list));
Console.WriteLine("Heap tree representation:");
TreeNode? tree = TreeNode.ListToTree(list.Cast<int?>().ToList());
PrintTree(tree);
}
/* Print priority queue */
public static void PrintHeap(PriorityQueue<int, int> queue) {
var newQueue = new PriorityQueue<int, int>(queue.UnorderedItems, queue.Comparer);
Console.Write("Heap array representation:");
List<int> list = [];
while (newQueue.TryDequeue(out int element, out _)) {
list.Add(element);
}
Console.WriteLine("Heap tree representation:");
Console.WriteLine(string.Join(',', list.ToList()));
TreeNode? tree = TreeNode.ListToTree(list.Cast<int?>().ToList());
PrintTree(tree);
}
}
+67
View File
@@ -0,0 +1,67 @@
/**
* File: TreeNode.cs
* Created Time: 2022-12-23
* Author: haptear (haptear@hotmail.com)
*/
namespace hello_algo.utils;
/* Binary tree node class */
public class TreeNode(int? x) {
public int? val = x; // Node value
public int height; // Node height
public TreeNode? left; // Reference to left child node
public TreeNode? right; // Reference to right child node
// For the serialization encoding rules, please refer to:
// https://www.hello-algo.com/chapter_tree/array_representation_of_tree/
// Array representation of binary tree:
// [1, 2, 3, 4, None, 6, 7, 8, 9, None, None, 12, None, None, 15]
// Linked list representation of binary tree:
// /——— 15
// /——— 7
// /——— 3
// | \——— 6
// | \——— 12
// ——— 1
// \——— 2
// | /——— 9
// \——— 4
// \——— 8
/* Deserialize a list into a binary tree: recursion */
static TreeNode? ListToTreeDFS(List<int?> arr, int i) {
if (i < 0 || i >= arr.Count || !arr[i].HasValue) {
return null;
}
TreeNode root = new(arr[i]) {
left = ListToTreeDFS(arr, 2 * i + 1),
right = ListToTreeDFS(arr, 2 * i + 2)
};
return root;
}
/* Deserialize a list into a binary tree */
public static TreeNode? ListToTree(List<int?> arr) {
return ListToTreeDFS(arr, 0);
}
/* Serialize a binary tree into a list: recursion */
static void TreeToListDFS(TreeNode? root, int i, List<int?> res) {
if (root == null)
return;
while (i >= res.Count) {
res.Add(null);
}
res[i] = root.val;
TreeToListDFS(root.left, 2 * i + 1, res);
TreeToListDFS(root.right, 2 * i + 2, res);
}
/* Serialize a binary tree into a list */
public static List<int?> TreeToList(TreeNode root) {
List<int?> res = [];
TreeToListDFS(root, 0, res);
return res;
}
}
+30
View File
@@ -0,0 +1,30 @@
/**
* File: Vertex.cs
* Created Time: 2023-02-06
* Author: zjkung1123 (zjkung1123@gmail.com), krahets (krahets@163.com)
*/
namespace hello_algo.utils;
/* Vertex class */
public class Vertex(int val) {
public int val = val;
/* Input value list vals, return vertex list vets */
public static Vertex[] ValsToVets(int[] vals) {
Vertex[] vets = new Vertex[vals.Length];
for (int i = 0; i < vals.Length; i++) {
vets[i] = new Vertex(vals[i]);
}
return vets;
}
/* Input vertex list vets, return value list vals */
public static List<int> VetsToVals(List<Vertex> vets) {
List<int> vals = [];
foreach (Vertex vet in vets) {
vals.Add(vet.val);
}
return vals;
}
}