From 22926b1043b45dc56ac1518fbf1a8c023c9813c3 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 21:04:27 +0530 Subject: [PATCH 01/90] pep8ify python --- .../code/python/Tree_example.py | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/contents/tree_traversal/code/python/Tree_example.py b/contents/tree_traversal/code/python/Tree_example.py index 67dd516a3..94cbce35c 100644 --- a/contents/tree_traversal/code/python/Tree_example.py +++ b/contents/tree_traversal/code/python/Tree_example.py @@ -15,30 +15,30 @@ def create_tree(node, num_row, num_child): return node -def DFS_recursive(node): +def dfs_recursive(node): if node.data != None: print(node.data) for child in node.children: - DFS_recursive(child) + dfs_recursive(child) -def DFS_recursive_postorder(node): +def dfs_recursive_postorder(node): for child in node.children: - DFS_recursive_postorder(child) + dfs_recursive_postorder(child) if node.data != None: print(node.data) # This assumes only 2 children, but accounts for other possibilities -def DFS_recursive_inorder_btree(node): +def dfs_recursive_inorder_btree(node): if (len(node.children) == 2): - DFS_recursive_inorder_btree(node.children[0]) + dfs_recursive_inorder_btree(node.children[0]) print(node.data) - DFS_recursive_inorder_btree(node.children[1]) + dfs_recursive_inorder_btree(node.children[1]) elif (len(node.children) == 1): - DFS_recursive_inorder_btree(node.children[0]) + dfs_recursive_inorder_btree(node.children[0]) print(node.data) elif (len(node.children) == 0): print(node.data) @@ -46,7 +46,7 @@ def DFS_recursive_inorder_btree(node): print("Not a binary tree!") -def DFS_stack(node): +def dfs_stack(node): stack = [] stack.append(node) @@ -60,7 +60,7 @@ def DFS_stack(node): stack.append(child) -def BFS_queue(node): +def bfs_queue(node): queue = [] queue.append(node) @@ -78,21 +78,21 @@ def main(): tree = create_tree(Node(), 3, 3) print("Recursive:") - DFS_recursive(tree) + dfs_recursive(tree) print("Recursive Postorder:") - DFS_recursive_postorder(tree) + dfs_recursive_postorder(tree) print("Stack:") - DFS_stack(tree) + dfs_stack(tree) print("Queue:") - BFS_queue(tree) + bfs_queue(tree) - binaryTree = create_tree(Node(), 3, 2) + binary_tree = create_tree(Node(), 3, 2) print("Recursive Inorder Binary Tree:") - DFS_recursive_inorder_btree(binaryTree) + dfs_recursive_inorder_btree(binary_tree) if __name__ == '__main__': main() From 933d66c1a50e545df3658a2c65d301e17f6e2f21 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 21:15:25 +0530 Subject: [PATCH 02/90] rename Tree_example.py --- .../code/python/{Tree_example.py => tree_traversal.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contents/tree_traversal/code/python/{Tree_example.py => tree_traversal.py} (100%) diff --git a/contents/tree_traversal/code/python/Tree_example.py b/contents/tree_traversal/code/python/tree_traversal.py similarity index 100% rename from contents/tree_traversal/code/python/Tree_example.py rename to contents/tree_traversal/code/python/tree_traversal.py From 57d11735a17cd6d7dc4153d95c843c9ccb9e2fb6 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 22:45:07 +0530 Subject: [PATCH 03/90] standardize python output --- .../code/python/tree_traversal.py | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py index 94cbce35c..98dad806d 100644 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -3,7 +3,6 @@ def __init__(self): self.data = None self.children = [] - def create_tree(node, num_row, num_child): node.data = num_row @@ -17,7 +16,7 @@ def create_tree(node, num_row, num_child): def dfs_recursive(node): if node.data != None: - print(node.data) + print(node.data, end=' ') for child in node.children: dfs_recursive(child) @@ -28,20 +27,20 @@ def dfs_recursive_postorder(node): dfs_recursive_postorder(child) if node.data != None: - print(node.data) + print(node.data, end=' ') # This assumes only 2 children, but accounts for other possibilities def dfs_recursive_inorder_btree(node): - if (len(node.children) == 2): + if len(node.children) == 2: dfs_recursive_inorder_btree(node.children[0]) - print(node.data) + print(node.data, end=' ') dfs_recursive_inorder_btree(node.children[1]) - elif (len(node.children) == 1): + elif len(node.children) == 1: dfs_recursive_inorder_btree(node.children[0]) - print(node.data) - elif (len(node.children) == 0): - print(node.data) + print(node.data, end=' ') + elif len(node.children) == 0: + print(node.data, end=' ') else: print("Not a binary tree!") @@ -53,7 +52,7 @@ def dfs_stack(node): temp = None while len(stack) > 0: - print(stack[-1].data) + print(stack[-1].data, end=' ') temp = stack.pop() for child in temp.children: @@ -67,7 +66,7 @@ def bfs_queue(node): temp = None while len(queue) > 0: - print(queue[0].data) + print(queue[0].data, end=' ') temp = queue.pop(0) for child in temp.children: @@ -75,24 +74,29 @@ def bfs_queue(node): def main(): - tree = create_tree(Node(), 3, 3) + tree = create_tree(Node(), 2, 3) - print("Recursive:") + print("[#] Recursive DFS:") dfs_recursive(tree) + print() - print("Recursive Postorder:") + print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) + print() - print("Stack:") + print("[#] Stack-based DFS :") dfs_stack(tree) + print() - print("Queue:") + print("[#] Queue-based BFS:") bfs_queue(tree) + print() binary_tree = create_tree(Node(), 3, 2) - print("Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder Binary Tree:") dfs_recursive_inorder_btree(binary_tree) + print() if __name__ == '__main__': main() From 12c02c68353a01b9393ce149359704e132903477 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:28:04 +0530 Subject: [PATCH 04/90] standardize c output --- .../tree_traversal/code/c/tree_traversal.c | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index 7fed9a16c..3c1db527b 100644 --- a/contents/tree_traversal/code/c/tree_traversal.c +++ b/contents/tree_traversal/code/c/tree_traversal.c @@ -35,7 +35,7 @@ void destroy_tree(struct node n) { } void dfs_recursive(struct node n) { - printf("%d\n", n.id); + printf("%d ", n.id); if (n.children) { for (size_t i = 0; i < n.children_size; ++i) { @@ -49,22 +49,22 @@ void dfs_recursive_postorder(struct node n) { dfs_recursive_postorder(n.children[i]); } - printf("%d\n", n.id); + printf("%d ", n.id); } void dfs_recursive_inorder_btree(struct node n) { switch (n.children_size) { case 2: dfs_recursive_inorder_btree(n.children[0]); - printf("%d\n", n.id); + printf("%d ", n.id); dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - printf("%d\n", n.id); + printf("%d ", n.id); break; case 0: - printf("%d\n", n.id); + printf("%d ", n.id); break; default: printf("This is not a binary tree.\n"); @@ -83,7 +83,7 @@ void dfs_stack(struct node n) { break; } - printf("%d\n", tmp->id); + printf("%d ", tmp->id); for (size_t i = 0; i < tmp->children_size; ++i) { stack_push(&stk, &tmp->children[i]); } @@ -103,7 +103,7 @@ void bfs_queue(struct node n) { break; } - printf("%d\n", tmp->id); + printf("%d ", tmp->id); for (size_t i = 0; i < tmp->children_size; ++i) { enqueue(&q, &tmp->children[i]); } @@ -113,9 +113,30 @@ void bfs_queue(struct node n) { } int main() { - struct node root = create_tree(3, 3); + struct node root = create_tree(2, 3); + + printf("[#] Recursive DFS:\n"); + dfs_recursive(root); + printf("\n"); + + printf("[#] Recursive Postorder DFS:\n"); + dfs_recursive_postorder(root); + printf("\n"); + + printf("[#] Stack-based DFS:\n"); + dfs_stack(root); + printf("\n"); + + printf("[#] Queue-based BFS:\n"); bfs_queue(root); + printf("\n"); + destroy_tree(root); + struct node root_binary = create_tree(3, 2); + printf("[#] Recursive Inorder DFS for Binary Tree:\n"); + dfs_recursive_inorder_btree(root_binary); + printf("\n"); + + destroy_tree(root_binary); return 0; -} From 920e3337fb6ee6ea30f509db12b7b59e1aa410ae Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:35:12 +0530 Subject: [PATCH 05/90] standardize c++ output --- .../tree_traversal/code/c++/tree_example.cpp | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index 9f2dd80e1..d109f11e5 100644 --- a/contents/tree_traversal/code/c++/tree_example.cpp +++ b/contents/tree_traversal/code/c++/tree_example.cpp @@ -17,7 +17,7 @@ struct node { // Simple recursive scheme for DFS void dfs_recursive(node const& n) { // Here we are doing something... - std::cout << n.value << '\n'; + std::cout << n.value << ' '; for (auto const& child : n.children) { dfs_recursive(child); } @@ -27,7 +27,7 @@ void dfs_recursive_postorder(node const& n) { for (auto const& child : n.children) { dfs_recursive_postorder(child); } - std::cout << n.value << '\n'; + std::cout << n.value << ' '; } @@ -35,15 +35,15 @@ void dfs_recursive_inorder_btree(node const& n) { switch (n.children.size()) { case 2: dfs_recursive_inorder_btree(n.children[0]); - std::cout << n.value << '\n'; + std::cout << n.value << ' '; dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - std::cout << n.value << '\n'; + std::cout << n.value << ' '; break; case 0: - std::cout << n.value << '\n'; + std::cout << n.value << ' '; break; default: std::cout << "This is not a binary tree.\n"; @@ -61,7 +61,7 @@ void dfs_stack(node const& n) { while (stack.size() > 0) { auto const& temp = *stack.top(); stack.pop(); - std::cout << temp.value << '\n'; + std::cout << temp.value << ' '; for (auto const& child : temp.children) { stack.push(&child); @@ -78,7 +78,7 @@ void bfs_queue(node const& n) { auto const& temp = *queue.front(); queue.pop(); - std::cout << temp.value << '\n'; + std::cout << temp.value << ' '; for (auto const& child : temp.children) { queue.push(&child); } @@ -100,18 +100,23 @@ node create_tree(size_t num_row, size_t num_child) { int main() { // Creating Tree in main - auto root = create_tree(3, 3); + auto root = create_tree(2, 3); auto binary_root = create_tree(3, 2); - std::cout << "DFS recursive:\n"; + std::cout << "[#] Recursive DFS:\n"; dfs_recursive(root); - std::cout << "DFS post order recursive:\n"; + std::cout << '\n'; + std::cout << "[#] Recursive Postorder DFS:\n"; dfs_recursive_postorder(root); - std::cout << "DFS inorder binary tree:\n"; - dfs_recursive_inorder_btree(binary_root); - std::cout << "DFS stack:\n"; + std::cout << '\n'; + std::cout << "[#] Stack-based DFS:\n"; dfs_stack(root); - std::cout << "BFS queue:\n"; + std::cout << '\n'; + std::cout << "[#] Queue-based BFS:\n"; bfs_queue(root); + std::cout << '\n'; + std::cout << "[#] Recursive Inorder DFS for Binary Tree:\n"; + dfs_recursive_inorder_btree(binary_root); + std::cout << '\n'; return 0; } From b3ad30c4b5ab3b2027bff7df52320e3f98b65f52 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:41:40 +0530 Subject: [PATCH 06/90] standardize rust output --- contents/tree_traversal/code/rust/tree.rs | 35 +++++++++++++---------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index f281e1a8c..35319454a 100644 --- a/contents/tree_traversal/code/rust/tree.rs +++ b/contents/tree_traversal/code/rust/tree.rs @@ -7,7 +7,7 @@ struct Node { } fn dfs_recursive(n: &Node) { - println!("{}", n.value); + print!("{} ", n.value); for child in &n.children { dfs_recursive(child); @@ -19,22 +19,22 @@ fn dfs_recursive_postorder(n: &Node) { dfs_recursive_postorder(child); } - println!("{}", n.value); + print!("{} ", n.value); } fn dfs_recursive_inorder_btree(n: &Node) { match &n.children[..] { [left, right] => { dfs_recursive_inorder_btree(left); - println!("{}", n.value); + print!("{} ", n.value); dfs_recursive_inorder_btree(right); } [left] => { dfs_recursive_inorder_btree(left); - println!("{}", n.value); + print!("{} ", n.value); } - [] => println!("{}", n.value), - _ => println!("This is not a binary tree."), + [] => print!("{} ", n.value), + _ => print!("This is not a binary tree. "), } } @@ -42,7 +42,7 @@ fn dfs_stack(n: &Node) { let mut stack = vec![n]; while let Some(current) = stack.pop() { - println!("{}", current.value); + print!("{} ", current.value); stack.extend(¤t.children); } } @@ -52,7 +52,7 @@ fn bfs_queue(n: &Node) { queue.push_back(n); while let Some(current) = queue.pop_front() { - println!("{}", current.value); + print!("{} ", current.value); queue.extend(¤t.children); } } @@ -78,19 +78,24 @@ fn create_tree(num_row: u64, num_child: u64) -> Node { fn main() { let root = create_tree(2, 3); - println!("Recursive DFS:"); + println!("[#] Recursive DFS:"); dfs_recursive(&root); + println!(); - println!("Stack DFS:"); + println!("[#] Recursive Postorder DFS:"); + dfs_recursive_postorder(&root); + println!(); + + println!("[#] Stack-based DFS:"); dfs_stack(&root); + println!(); - println!("Queue BFS:"); + println!("[#] Queue-based BFS:"); bfs_queue(&root); + println!(); - println!("Recursive post-order DFS:"); - dfs_recursive_postorder(&root); - - println!("Recursive in-order DFS BTree:"); + println!("[#] Recursive Inorder DFS for Binary Tree:"); let root_binary = create_tree(3, 2); dfs_recursive_inorder_btree(&root_binary); + println!(); } From ba5824b30d9a780ee857bfe84970683f325cf44c Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:48:43 +0530 Subject: [PATCH 07/90] standardize javascript output --- .../tree_traversal/code/javascript/tree.js | 25 ++++++++++++++----- 1 file changed, 19 insertions(+), 6 deletions(-) diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index b6705bfdd..24392a259 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -10,13 +10,13 @@ function createTree(rows, children) { } function dfsPreorder(tree) { - console.log(tree.id); + process.stdout.write(tree.id + " "); tree.children.forEach(dfsPreorder); } function dfsPostorder(tree) { tree.children.forEach(dfsPostorder); - console.log(tree.id); + process.stdout.write(tree.id + " "); } function dfsInorder(tree) { @@ -29,7 +29,7 @@ function dfsInorder(tree) { } dfsInorder(tree.children[0]); - console.log(tree.id); + process.stdout.write(tree.id + " "); dfsInorder(tree.children[1]); } @@ -37,7 +37,7 @@ function dfsIterative(tree) { const stack = [tree]; while (stack.length > 0) { const current = stack.pop(); - console.log(current.id); + process.stdout.write(current.id + " "); stack.push(...current.children); } } @@ -46,13 +46,26 @@ function bfs(tree) { const queue = [tree]; while (queue.length > 0) { const current = queue.shift(); - console.log(current.id); + process.stdout.write(current.id + " "); queue.push(...current.children); } } -const root = createTree(3, 3); +const root = createTree(2, 3); +console.log("[#] Recursive DFS:"); dfsPreorder(root); +console.log(); +console.log("[#] Recursive Postorder DFS:"); dfsPostorder(root); +console.log(); +console.log("[#] Stack-based DFS:"); dfsIterative(root); +console.log(); +console.log("[#] Queue-based BFS:"); bfs(root); +console.log(); +const root_binary = createTree(3, 2); +console.log("[#] Recursive Inorder DFS for Binary Tree:"); +dfsInorder(root_binary); +console.log(); + From 6726ed39b03915fb3b97e486b388bc52a6a05642 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 01:04:52 +0530 Subject: [PATCH 08/90] standardize julia output --- contents/tree_traversal/code/julia/Tree.jl | 34 ++++++++++++---------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index 8e7893cd1..652048c71 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -1,4 +1,4 @@ -using DataStructures +using DataStructures, Printf struct Node children::Vector{Node} @@ -8,7 +8,7 @@ end function DFS_recursive(n::Node) # Here we are doing something... - println(n.ID) + @printf("%i ", n.ID) for child in n.children DFS_recursive(child) @@ -22,7 +22,7 @@ function DFS_recursive_postorder(n::Node) end # Here we are doing something... - println(n.ID) + @printf("%i ", n.ID) end # This assumes only 2 children, but accounts for other possibilities @@ -30,13 +30,13 @@ function DFS_recursive_inorder_btree(n::Node) if (length(n.children) == 2) DFS_recursive_inorder_btree(n.children[1]) - println(n.ID) + @printf("%i ", n.ID) DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - println(n.ID) + @printf("%i ", n.ID) elseif (length(n.children) == 0) - println(n.ID) + @printf("%i ", n.ID) else println("Not a binary tree!") end @@ -47,7 +47,7 @@ function DFS_stack(n::Node) push!(s, n) while(length(s) > 0) - println(top(s).ID) + @printf("%i ", top(s).ID) temp = pop!(s) for child in temp.children push!(s, child) @@ -60,7 +60,7 @@ function BFS_queue(n::Node) enqueue!(q, n) while(length(q) > 0) - println(front(q).ID) + @printf("%i ", first(q).ID) temp = dequeue!(q) for child in temp.children enqueue!(q, child) @@ -84,26 +84,28 @@ function create_tree(num_row::Int64, num_child::Int64) end function main() - - println("Creating Tree") root = create_tree(2, 3) - println("Using recursive DFS:") + println("[#] Recursive DFS:") DFS_recursive(root); + println() - println("Using recursive DFS with post-order traversal:") + println("[#] Recursive Postorder DFS:") DFS_recursive_postorder(root); + println() - println("Using stack-based DFS:") + println("[#] Stack-based DFS:") DFS_stack(root); + println() - println("Using queue-based BFS:") + println("[#] Queue-based BFS:") BFS_queue(root); + println() - println("Creating binary tree to test in-order traversal.") root_binary = create_tree(3,2) - println("Using In-order DFS:") + println("[#] Recursive Inorder DFS for Binary Tree:") DFS_recursive_inorder_btree(root_binary) + println() end main() From 9cb22f3d8f7e12bbbe5eaa045ddb66636b04b58f Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Fri, 3 Sep 2021 23:25:28 +0200 Subject: [PATCH 09/90] Standardized Coconut output --- .../tree_traversal/code/coconut/tree_traversal.coco | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index c7433fea2..077ea2e35 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -62,22 +62,22 @@ if __name__ =='__main__': tree = create_tree(3, 3) # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("Recursive DFS:") + print("[#] Recursive DFS:") dfs_recursive(tree) print() # Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 - print("Recursive Postorder DFS:") + print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) print() # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("Stack (DFS):") + print("[#] Stack (DFS):") dfs_stack(tree) print() # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 - print("Queue (BFS):") + print([#] "Queue (BFS):") bfs_queue(tree) print() @@ -85,7 +85,7 @@ if __name__ =='__main__': binary_tree = create_tree(3, 2) # Should print: 1 2 1 3 1 2 1 - print("Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From 0dde208d6380943247393d5f8a999cf5e0715926 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:00:02 +0530 Subject: [PATCH 10/90] fix coconut --- .../tree_traversal/code/coconut/tree_traversal.coco | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index 077ea2e35..ad7be7932 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -50,8 +50,8 @@ def bfs_queue(node is Node): def create_tree(num_rows, num_child): """Creates a simple tree, where every node has 'num_child' children and is 'num_rows' deep.""" - if num_rows == 1: - return Node(1, ()) + if num_rows == 0: + return Node(0, ()) else: return Node(num_rows, tuple(create_tree(num_rows-1, num_child) for _ in range(num_child))) @@ -59,7 +59,7 @@ def create_tree(num_rows, num_child): if __name__ =='__main__': # A ternary tree for testing - tree = create_tree(3, 3) + tree = create_tree(2, 3) # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Recursive DFS:") @@ -72,12 +72,12 @@ if __name__ =='__main__': print() # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("[#] Stack (DFS):") + print("[#] Stack-based DFS:") dfs_stack(tree) print() # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 - print([#] "Queue (BFS):") + print("[#] Queue-based BFS:") bfs_queue(tree) print() @@ -85,7 +85,7 @@ if __name__ =='__main__': binary_tree = create_tree(3, 2) # Should print: 1 2 1 3 1 2 1 - print("[#] Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From bdd40d20f8c28a5f9a0cedbc2d82c0f33f4cf193 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:12:33 +0530 Subject: [PATCH 11/90] standardize go output --- .../code/golang/treetraversal.go | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index 548f552f7..deba1347d 100644 --- a/contents/tree_traversal/code/golang/treetraversal.go +++ b/contents/tree_traversal/code/golang/treetraversal.go @@ -8,7 +8,7 @@ type node struct { } func dfsRecursive(n *node) { - fmt.Println(n.id) + fmt.Printf("%d ", n.id) for _, child := range n.children { dfsRecursive(child) } @@ -18,20 +18,20 @@ func dfsRecursivePostorder(n *node) { for _, child := range n.children { dfsRecursive(child) } - fmt.Println(n.id) + fmt.Printf("%d ", n.id) } func dfsRecursiveInorderBtree(n *node) { switch len(n.children) { case 2: dfsRecursiveInorderBtree(n.children[0]) - fmt.Println(n.id) + fmt.Printf("%d ", n.id) dfsRecursiveInorderBtree(n.children[1]) case 1: dfsRecursiveInorderBtree(n.children[0]) - fmt.Println(n.id) + fmt.Printf("%d ", n.id) case 0: - fmt.Println(n.id) + fmt.Printf("%d ", n.id) default: fmt.Println("This is not a binary tree") } @@ -43,7 +43,7 @@ func dfsStack(n *node) { for len(stack) > 0 { cur := stack[0] stack = stack[1:] - fmt.Println(cur.id) + fmt.Printf("%d ", cur.id) stack = append(cur.children, stack...) } } @@ -54,7 +54,7 @@ func bfsQueue(n *node) { for len(queue) > 0 { cur := queue[0] queue = queue[1:] - fmt.Println(cur.id) + fmt.Printf("%d ", cur.id) queue = append(queue, cur.children...) } } @@ -74,17 +74,27 @@ func createTree(numRow, numChild int) *node { } func main() { - root := createTree(3, 3) + root := createTree(2, 3) binTree := createTree(3, 2) - fmt.Println("DFS recursive:") + fmt.Println("[#] DFS Recursive:") dfsRecursive(root) - fmt.Println("DFS post order recursive:") + fmt.Println() + + fmt.Println("[#] DFS Postorder Recursive:") dfsRecursivePostorder(root) - fmt.Println("DFS inorder binary tree:") - dfsRecursiveInorderBtree(binTree) - fmt.Println("DFS stack:") + fmt.Println() + + fmt.Println("[#] Stack-based DFS:") dfsStack(root) - fmt.Println("BFS queue:") + fmt.Println() + + fmt.Println("[#] Queue-based BFS:") bfsQueue(root) + fmt.Println() + + fmt.Println("[#] DFS Inorder for Binary Tree:") + dfsRecursiveInorderBtree(binTree) + fmt.Println() + } From 02c65371ab7c0505d15564de8033a4c26e9d9f90 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:25:51 +0530 Subject: [PATCH 12/90] standardize common lisp output --- .../code/clisp/tree-traversal.lisp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 417a6f242..31395f3ac 100644 --- a/contents/tree_traversal/code/clisp/tree-traversal.lisp +++ b/contents/tree_traversal/code/clisp/tree-traversal.lisp @@ -58,36 +58,41 @@ (defun make-tree (num-rows num-child) "Creates a simple tree, where every node has 'num-child' children and is 'num-rows' deep." ;; A tree with 0 rows can't be created. - (if (eql num-rows 1) + (if (eql num-rows 0) (make-node - :data 1 + :data 0 :children nil) (make-node :data num-rows :children (loop repeat num-child collect (make-tree (1- num-rows) num-child))))) ;; A tree for testing -(defvar tree (make-tree 3 3)) +(defvar tree (make-tree 2 3)) ;; A binary tree for testing (defvar binary-tree (make-tree 3 2)) ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 +(format t "[#] Recursive DFS:~%") (dfs-recursive tree) (format t "~%") ;; Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 +(format t "[#] Recursive Postorder DFS:~%") (dfs-recursive-postorder tree) (format t "~%") -;; Should print: 1 2 1 3 1 2 1 -(dfs-recursive-inorder-btree binary-tree) -(format t "~%") - ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 +(format t "[#] Stack-based DFS:~%") (dfs-stack tree) (format t "~%") ;; Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 +(format t "[#] Queue-based BFS:~%") (bfs-queue tree) (format t "~%") + +;; Should print: 1 2 1 3 1 2 1 +(format t "[#] Recursive Inorder DFS for Binary Tree:~%") +(dfs-recursive-inorder-btree binary-tree) +(format t "~%") From b8d4679df76141d9a2a129af9264701b58d33565 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Sat, 4 Sep 2021 04:42:51 +0200 Subject: [PATCH 13/90] Verlet Integration: Output standardization (#855) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Standardize julia output * Standardize kotlin output This also fixes a previous bug, which caused the time and velocity values to not get printed correctly. * Standardized c output * Standardized cpp output * Standardized lisp output * Standardized fortran output I was not able to prevent the preceding whitespaces, but they can just be trimmed. * Standardized go output * Standardized java output * Standardize javascript output * Standardize nim output * Standardize python output * Standardize ruby output As the original implementation only returned the time and not the velocity, the code needed to be adjusted a bit. Now it returns the two values as an array which gets deconstructed and printed. * Standardize rust output * Standardize swift output * Standardized haskell output * Standardized haskell output (no quote marks) * attempt at fix for asm Co-authored-by: Jérémie Gillet Co-authored-by: James Schloss --- .../verlet_integration/code/asm-x64/verlet.s | 6 ++--- .../verlet_integration/code/c++/verlet.cpp | 10 ++++----- contents/verlet_integration/code/c/verlet.c | 16 +++++++++----- .../verlet_integration/code/clisp/verlet.lisp | 15 ++++++++----- .../code/fortran/verlet.f90 | 17 ++++++++++---- .../verlet_integration/code/golang/verlet.go | 22 +++++++++---------- .../verlet_integration/code/haskell/verlet.hs | 18 +++++++++++---- .../verlet_integration/code/java/Verlet.java | 16 +++++++++----- .../code/javascript/verlet.js | 15 ++++++++----- .../verlet_integration/code/julia/verlet.jl | 18 ++++++++++----- .../verlet_integration/code/kotlin/verlet.kt | 15 ++++++++----- .../verlet_integration/code/nim/verlet.nim | 15 ++++++++----- .../verlet_integration/code/python/verlet.py | 22 +++++++++---------- .../verlet_integration/code/ruby/verlet.rb | 19 ++++++++++++---- .../verlet_integration/code/rust/verlet.rs | 21 ++++++++++-------- .../code/swift/verlet.swift | 15 ++++++++----- 16 files changed, 167 insertions(+), 93 deletions(-) diff --git a/contents/verlet_integration/code/asm-x64/verlet.s b/contents/verlet_integration/code/asm-x64/verlet.s index ed2521f78..d9617fe33 100644 --- a/contents/verlet_integration/code/asm-x64/verlet.s +++ b/contents/verlet_integration/code/asm-x64/verlet.s @@ -4,9 +4,9 @@ zero: .double 0.0 two: .double 2.0 half: .double 0.5 - verlet_fmt: .string "Time for Verlet integration is: %lf\n" - stormer_fmt: .string "Time and Velocity for Stormer Verlet Integration is: %lf, %lf\n" - velocity_fmt: .string "Time and Velocity for Velocity Verlet Integration is: %lf, %lf\n" + verlet_fmt: .string "[#] Time for Verlet integration is:\n%lf\n" + stormer_fmt: .string "[#] Time for Stormer Verlet Integration is:\n%lf\n[#] Velocity for Stormer Verlet Integration is:\n%lf\n" + velocity_fmt: .string "[#] Time for Velocity Verlet Integration is:\n%lf\n[#] Velocity for Velocity Verlet Integration is:\n%lf\n" pos: .double 5.0 acc: .double -10.0 dt: .double 0.01 diff --git a/contents/verlet_integration/code/c++/verlet.cpp b/contents/verlet_integration/code/c++/verlet.cpp index 473f92ee9..946ddc618 100644 --- a/contents/verlet_integration/code/c++/verlet.cpp +++ b/contents/verlet_integration/code/c++/verlet.cpp @@ -64,19 +64,19 @@ int main() { // each of these functions. double time = verlet(5.0, -10, 0.01); - std::cout << "Time for Verlet integration is: " \ + std::cout << "[#] Time for Verlet integration is:\n" \ << time << std::endl; timestep timestep_sv = stormer_verlet(5.0, -10, 0.01); - std::cout << "Time for Stormer Verlet integration is: " \ + std::cout << "[#] Time for Stormer Verlet integration is:\n" \ << timestep_sv.time << std::endl; - std::cout << "Velocity for Stormer Verlet integration is: " \ + std::cout << "[#] Velocity for Stormer Verlet integration is:\n" \ << timestep_sv.vel << std::endl; timestep timestep_vv = velocity_verlet(5.0, -10, 0.01); - std::cout << "Time for velocity Verlet integration is: " \ + std::cout << "[#] Time for velocity Verlet integration is:\n" \ << timestep_vv.time << std::endl; - std::cout << "Velocity for velocity Verlet integration is: " \ + std::cout << "[#] Velocity for velocity Verlet integration is:\n" \ << timestep_vv.vel << std::endl; return 0; diff --git a/contents/verlet_integration/code/c/verlet.c b/contents/verlet_integration/code/c/verlet.c index c56a3cc5b..c42254974 100644 --- a/contents/verlet_integration/code/c/verlet.c +++ b/contents/verlet_integration/code/c/verlet.c @@ -46,16 +46,20 @@ int main() { double time, vel; verlet(&time, 5.0, -10, 0.01); - printf("Time for Verlet integration is: %lf\n", - time); + printf("[#] Time for Verlet integration is:\n"); + printf("%lf\n", time); stormer_verlet(&time, &vel, 5.0, -10, 0.01); - printf("Time and velocity for Stormer Verlet integration is: %lf, %lf\n", - time, vel); + printf("[#] Time for Stormer Verlet integration is:\n"); + printf("%lf\n", time); + printf("[#] Velocity for Stormer Verlet integration is:\n"); + printf("%lf\n", vel); velocity_verlet(&time, &vel, 5.0, -10, 0.01); - printf("Time and velocity for velocity Verlet integration is: %lf, %lf\n", - time, vel); + printf("[#] Time for velocity Verlet integration is:\n"); + printf("%lf\n", time); + printf("[#] Velocity for Stormer Verlet integration is:\n"); + printf("%lf\n", vel); return 0; } diff --git a/contents/verlet_integration/code/clisp/verlet.lisp b/contents/verlet_integration/code/clisp/verlet.lisp index 726b1f1c6..f08f2a7e6 100644 --- a/contents/verlet_integration/code/clisp/verlet.lisp +++ b/contents/verlet_integration/code/clisp/verlet.lisp @@ -34,12 +34,17 @@ while (> p 0) finally (return (list time vel)))) -(format T "Time for Verlet integration: ~d~%" (verlet 5 -10 0.01)) +(format T "[#] Time for Verlet integration:~%") +(format T "~d~%" (verlet 5 -10 0.01)) (defvar stormer-verlet-result (stormer-verlet 5 -10 0.01)) -(format T "Time for Stormer Verlet integration is: ~d~%" (first stormer-verlet-result)) -(format T "Velocity for Stormer Verlet integration is: ~d~%" (second stormer-verlet-result)) +(format T "[#] Time for Stormer Verlet integration is:~%") +(format T "~d~%" (first stormer-verlet-result)) +(format T "[#] Velocity for Stormer Verlet integration is:~%") +(format T "~d~%" (second stormer-verlet-result)) (defvar velocity-verlet-result (velocity-verlet 5 -10 0.01)) -(format T "Time for velocity Verlet integration is: ~d~%" (first velocity-verlet-result)) -(format T "Velocity for velocity Verlet integration is: ~d~%" (second velocity-verlet-result)) +(format T "[#] Time for velocity Verlet integration is:~%") +(format T "~d~%" (first velocity-verlet-result)) +(format T "[#] Velocity for velocity Verlet integration is:~%") +(format T "~d~%" (second velocity-verlet-result)) \ No newline at end of file diff --git a/contents/verlet_integration/code/fortran/verlet.f90 b/contents/verlet_integration/code/fortran/verlet.f90 index 417fc77b7..6999df1e5 100644 --- a/contents/verlet_integration/code/fortran/verlet.f90 +++ b/contents/verlet_integration/code/fortran/verlet.f90 @@ -91,18 +91,27 @@ SUBROUTINE velocity_verlet(pos, acc, dt, time, vel) ! Verlet CALL verlet(pos, acc, dt, time) - WRITE(*,*) 'Time for Verlet integration: ', time + WRITE(*,*) '[#] Time for Verlet integration:' + WRITE(*,*) time ! stormer Verlet pos = 5d0 CALL stormer_verlet(pos, acc, dt, time, vel) - WRITE(*,*) 'Time for Stormer-Verlet integration: ', time + WRITE(*,*) '[#] Time for Stormer Verlet integration:' + WRITE(*,*) time + WRITE(*,*) '[#] Velocity for Stormer Verlet integration:' + WRITE(*,*) vel + + ! Velocity Verlet pos = 5d0 CALL velocity_verlet(pos, acc, dt, time, vel) - WRITE(*,*) 'Time for Velocity-Verlet integration: ', time - + WRITE(*,*) '[#] Time for velocity Verlet integration:' + WRITE(*,*) time + WRITE(*,*) '[#] Velocity for velocity Verlet integration:' + WRITE(*,*) vel + END PROGRAM verlet_integration diff --git a/contents/verlet_integration/code/golang/verlet.go b/contents/verlet_integration/code/golang/verlet.go index 778521da4..a7cd1c86b 100644 --- a/contents/verlet_integration/code/golang/verlet.go +++ b/contents/verlet_integration/code/golang/verlet.go @@ -43,18 +43,18 @@ func velocityVerlet(pos, acc, dt float64) (time, vel float64) { func main() { time := verlet(5., -10., .01) - fmt.Println("Verlet") - fmt.Println("Time:", time) - fmt.Println() + fmt.Println("[#] Time for Verlet integration is:") + fmt.Println(time) time, vel := stormerVerlet(5., -10., .01) - fmt.Println("Stormer-Verlet") - fmt.Println("Time:", time) - fmt.Println("Velocity:", vel) - fmt.Println() - + fmt.Println("[#] Time for Stormer Verlet integration is:") + fmt.Println(time) + fmt.Println("[#] Velocity for Stormer Verlet integration is:") + fmt.Println(vel) + time, vel = velocityVerlet(5., -10., .01) - fmt.Println("Velocity Verlet") - fmt.Println("Time:", time) - fmt.Println("Velocity:", vel) + fmt.Println("[#] Time for velocity Verlet integration is:") + fmt.Println(time) + fmt.Println("[#] Velocity for velocity Verlet integration is:") + fmt.Println(vel) } diff --git a/contents/verlet_integration/code/haskell/verlet.hs b/contents/verlet_integration/code/haskell/verlet.hs index df82004e6..675c7f39b 100644 --- a/contents/verlet_integration/code/haskell/verlet.hs +++ b/contents/verlet_integration/code/haskell/verlet.hs @@ -48,7 +48,17 @@ main = do dt = 0.001 freefall _ = -10 aboveGround (x, _, _, _) = x > 0 - integrate m = last $ takeWhile aboveGround $ trajectory m freefall dt p0 - print $ integrate verlet - print $ integrate stormerVerlet - print $ integrate velocityVerlet + timeVelocity m = + let (_, v, _, t) = last $ takeWhile aboveGround $ trajectory m freefall dt p0 + in (show t, show v) + + putStrLn "[#] Time for Verlet integration is:" + putStrLn $ fst $ timeVelocity verlet + putStrLn "[#] Time for Stormer Verlet integration is:" + putStrLn $ fst $ timeVelocity stormerVerlet + putStrLn "[#] Velocity for Stormer Verlet integration is:" + putStrLn $ snd $ timeVelocity stormerVerlet + putStrLn "[#] Time for velocity Verlet integration is:" + putStrLn $ fst $ timeVelocity velocityVerlet + putStrLn "[#] Velocity for velocity Verlet integration is:" + putStrLn $ snd $ timeVelocity velocityVerlet diff --git a/contents/verlet_integration/code/java/Verlet.java b/contents/verlet_integration/code/java/Verlet.java index a7bb94447..35387cf8b 100644 --- a/contents/verlet_integration/code/java/Verlet.java +++ b/contents/verlet_integration/code/java/Verlet.java @@ -65,14 +65,20 @@ static VerletValues velocity_verlet(double pos, double acc, double dt) { public static void main(String[] args) { double verletTime = verlet(5.0, -10, 0.01); - System.out.println("Time for Verlet integration is: " + verletTime); + System.out.println("[#] Time for Verlet integration is:"); + System.out.println(verletTime); VerletValues stormerVerlet = stormer_verlet(5.0, -10, 0.01); - System.out.println("Time for Stormer Verlet integration is: " + stormerVerlet.time); - System.out.println("Velocity for Stormer Verlet integration is: " + stormerVerlet.vel); + System.out.println("[#] Time for Stormer Verlet integration is:"); + System.out.println(stormerVerlet.time); + System.out.println("[#] Velocity for Stormer Verlet integration is:"); + System.out.println(stormerVerlet.vel); VerletValues velocityVerlet = velocity_verlet(5.0, -10, 0.01); - System.out.println("Time for velocity Verlet integration is: " + velocityVerlet.time); - System.out.println("Velocity for velocity Verlet integration is: " + velocityVerlet.vel); + System.out.println("[#] Time for velocity Verlet integration is:"); + System.out.println(velocityVerlet.time); + System.out.println("[#] Velocity for velocity Verlet integration is:"); + System.out.println(velocityVerlet.vel); + } } diff --git a/contents/verlet_integration/code/javascript/verlet.js b/contents/verlet_integration/code/javascript/verlet.js index 013a7fa3f..7ea09e187 100644 --- a/contents/verlet_integration/code/javascript/verlet.js +++ b/contents/verlet_integration/code/javascript/verlet.js @@ -45,12 +45,17 @@ function velocityVerlet(pos, acc, dt) { } const time = verlet(5, -10, 0.01); -console.log(`Time for Verlet integration is: ${time}\n`); +console.log(`[#] Time for Verlet integration is:`); +console.log(`${time}`); const stormer = stormerVerlet(5, -10, 0.01); -console.log(`Time for Stormer Verlet integration is: ${stormer.time}`); -console.log(`Velocity for Stormer Verlet integration is: ${stormer.vel}\n`); +console.log(`[#] Time for Stormer Verlet integration is:`); +console.log(`${stormer.time}`); +console.log(`[#] Velocity for Stormer Verlet integration is:`); +console.log(`${stormer.vel}`); const velocity = velocityVerlet(5, -10, 0.01); -console.log(`Time for Velocity Verlet integration is: ${velocity.time}`); -console.log(`Velocity for Velocity Verlet integration is: ${velocity.vel}\n`); +console.log(`[#] Time for velocity Verlet integration is:`); +console.log(`${velocity.time}`); +console.log(`[#] Velocity for velocity Verlet integration is:`); +console.log(`${velocity.vel}`); diff --git a/contents/verlet_integration/code/julia/verlet.jl b/contents/verlet_integration/code/julia/verlet.jl index b55b85a9e..b9edcea98 100644 --- a/contents/verlet_integration/code/julia/verlet.jl +++ b/contents/verlet_integration/code/julia/verlet.jl @@ -46,15 +46,21 @@ end function main() time = verlet(5.0, -10.0, 0.01); - println("Time for Verlet integration is: $(time)\n") + println("[#] Time for Verlet integration is:") + println("$(time)") time, vel = stormer_verlet(5.0, -10.0, 0.01); - println("Time for Stormer Verlet integration is: $(time)") - println("Velocity for Stormer Verlet integration is: $(vel)\n") - + println("[#] Time for Stormer Verlet integration is:") + println("$(time)") + println("[#] Velocity for Stormer Verlet integration is:") + println("$(vel)") + time, vel = velocity_verlet(5.0, -10.0, 0.01); - println("Time for velocity Verlet integration is: $(time)") - println("Velocity for velocity Verlet integration is: $(vel)\n") + println("[#] Time for velocity Verlet integration is:") + println("$(time)") + println("[#] Velocity for velocity Verlet integration is:") + println("$(vel)") + end main() diff --git a/contents/verlet_integration/code/kotlin/verlet.kt b/contents/verlet_integration/code/kotlin/verlet.kt index c2d41b3ff..79bee7b6a 100644 --- a/contents/verlet_integration/code/kotlin/verlet.kt +++ b/contents/verlet_integration/code/kotlin/verlet.kt @@ -43,13 +43,18 @@ fun velocityVerlet(_pos: Double, acc: Double, dt: Double): VerletValues { fun main(args: Array) { val verletTime = verlet(5.0, -10.0, 0.01) - println("Time for Verlet integration is: $verletTime") + println("[#] Time for Verlet integration is:") + println("$verletTime") val stormerVerlet = stormerVerlet(5.0, -10.0, 0.01) - println("Time for Stormer Verlet integration is: $stormerVerlet.time") - println("Velocity for Stormer Verlet integration is: $stormerVerlet.vel") + println("[#] Time for Stormer Verlet integration is:") + println("${stormerVerlet.time}") + println("[#] Velocity for Stormer Verlet integration is:") + println("${stormerVerlet.vel}") val velocityVerlet = velocityVerlet(5.0, -10.0, 0.01) - println("Time for Velocity Verlet integration is: $velocityVerlet.time") - println("Velocity for Velocity Verlet integration is: $velocityVerlet.vel") + println("[#] Time for Velocity Verlet integration is:") + println("${velocityVerlet.time}") + println("[#] Velocity for Velocity Verlet integration is:") + println("${velocityVerlet.vel}") } diff --git a/contents/verlet_integration/code/nim/verlet.nim b/contents/verlet_integration/code/nim/verlet.nim index d88a2e586..2e92b57c4 100644 --- a/contents/verlet_integration/code/nim/verlet.nim +++ b/contents/verlet_integration/code/nim/verlet.nim @@ -46,12 +46,17 @@ func velocityVerlet(pos_in, acc, dt: float): (float, float) = when isMainModule: let timeV = verlet(5.0, -10.0, 0.01) - echo "Time for Verlet integration is: ", timeV + echo "[#] Time for Verlet integration is:" + echo timeV let (timeSV, velSV) = stormerVerlet(5.0, -10.0, 0.01) - echo "Time for Stormer Verlet integration is: ", timeSV - echo "Velocity for Stormer Verlet integration is: ", velSV + echo "[#] Time for Stormer Verlet integration is:" + echo timeSV + echo "[#] Velocity for Stormer Verlet integration is:" + echo velSV let (timeVV, velVV) = velocityVerlet(5.0, -10.0, 0.01) - echo "Time for velocity Verlet integration is: ", timeVV - echo "Velocity for velocity Verlet integration is: ", velVV + echo "[#] Time for velocity Verlet integration is:" + echo timeVV + echo "[#] Velocity for velocity Verlet integration is:" + echo velVV diff --git a/contents/verlet_integration/code/python/verlet.py b/contents/verlet_integration/code/python/verlet.py index c921d1954..18dc627d3 100644 --- a/contents/verlet_integration/code/python/verlet.py +++ b/contents/verlet_integration/code/python/verlet.py @@ -35,21 +35,21 @@ def velocity_verlet(pos, acc, dt): def main(): time = verlet(5, -10, 0.01) - print("Verlet") - print("Time: {:.10f}".format(time)) - print() + print("[#] Time for Verlet integration is:") + print("{:.10f}".format(time)) time, vel = stormer_verlet(5, -10, 0.01) - print("Stormer-Verlet") - print("Time: {:.10f}".format(time)) - print("Velocity: {:.10f}".format(vel)) - print() + print("[#] Time for Stormer Verlet integration is:") + print("{:.10f}".format(time)) + print("[#] Velocity for Stormer Verlet integration is:") + print("{:.10f}".format(vel)) time, vel = velocity_verlet(5, -10, 0.01) - print("Velocity Verlet") - print("Time: {:.10f}".format(time)) - print("Velocity: {:.10f}".format(vel)) - print() + print("[#] Time for velocity Verlet integration is:") + print("{:.10f}".format(time)) + print("[#] Velocity for velocity Verlet integration is:") + print("{:.10f}".format(vel)) + if __name__ == '__main__': main() diff --git a/contents/verlet_integration/code/ruby/verlet.rb b/contents/verlet_integration/code/ruby/verlet.rb index 10246c6b7..4a6c38a48 100644 --- a/contents/verlet_integration/code/ruby/verlet.rb +++ b/contents/verlet_integration/code/ruby/verlet.rb @@ -27,7 +27,7 @@ def stormer_verlet(pos, acc, dt) vel += acc*dt end - return time + return time, vel end @@ -41,10 +41,21 @@ def velocity_verlet(pos, acc, dt) vel += acc*dt end - return time + return time, vel end +puts "[#] Time for Verlet integration is:" p verlet(5.0, -10, 0.01) -p stormer_verlet(5.0, -10, 0.01) -p velocity_verlet(5.0, -10, 0.01) + +time, vel = stormer_verlet(5.0, -10, 0.01) +puts "[#] Time for Stormer Verlet integration is:" +p time +puts "[#] Velocity for Stormer Verlet integration is:" +p vel + +time, vel = velocity_verlet(5.0, -10, 0.01) +puts "[#] Time for velocity Verlet integration is:" +p time +puts "[#] Velocity for velocity Verlet integration is:" +p vel diff --git a/contents/verlet_integration/code/rust/verlet.rs b/contents/verlet_integration/code/rust/verlet.rs index 490994da2..f765da864 100644 --- a/contents/verlet_integration/code/rust/verlet.rs +++ b/contents/verlet_integration/code/rust/verlet.rs @@ -49,13 +49,16 @@ fn main() { let (time_sv, vel_sv) = stormer_verlet(5.0, -10.0, 0.01); let (time_vv, vel_vv) = velocity_verlet(5.0, -10.0, 0.01); - println!("Time for original Verlet integration: {}", time_v); - println!( - "Time and velocity for Stormer Verlet integration: {}, {}", - time_sv, vel_sv - ); - println!( - "Time and velocity for velocity Verlet integration: {}, {}", - time_vv, vel_vv - ); + println!("[#] Time for Verlet integration is:"); + println!("{}", time_v); + + println!("[#] Time for Stormer Verlet integration is:"); + println!("{}", time_sv); + println!("[#] Velocity for Stormer Verlet integration is:"); + println!("{}", vel_sv); + + println!("[#] Time for velocity Verlet integration is:"); + println!("{}", time_vv); + println!("[#] Velocity for velocity Verlet integration is:"); + println!("{}", vel_vv); } diff --git a/contents/verlet_integration/code/swift/verlet.swift b/contents/verlet_integration/code/swift/verlet.swift index a241660a9..7991a0082 100644 --- a/contents/verlet_integration/code/swift/verlet.swift +++ b/contents/verlet_integration/code/swift/verlet.swift @@ -50,15 +50,20 @@ func velocityVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: func main() { let verletTime = verlet(pos: 5.0, acc: -10.0, dt: 0.01) - print("Time for Verlet integration is: \(verletTime)") + print("[#] Time for Verlet integration is:") + print("\(verletTime)") let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01); - print("Time for Stormer Verlet integration is: \(stormer.time)") - print("Velocity for Stormer Verlet integration is: \(stormer.vel)") + print("[#] Time for Stormer Verlet integration is:") + print("\(stormer.time)") + print("[#] Velocity for Stormer Verlet integration is:") + print("\(stormer.vel)") let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01) - print("Time for velocity Verlet integration is: \(velVerlet.time)") - print("Velocity for velocity Verlet integration is: \(velVerlet.vel)") + print("[#] Time for velocity Verlet integration is:") + print("\(velVerlet.time)") + print("[#] Velocity for velocity Verlet integration is:") + print("\(velVerlet.vel)") } main() From 62d8795ce87f282472bf1dc01ccf1151a2974d42 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 11:59:11 +0530 Subject: [PATCH 14/90] standardize php output --- .../code/php/tree_traversal.php | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index fde55046a..0951cea79 100644 --- a/contents/tree_traversal/code/php/tree_traversal.php +++ b/contents/tree_traversal/code/php/tree_traversal.php @@ -40,9 +40,7 @@ class TreeTraversal { public static function DFSRecursive(Tree $tree): void { - if ($tree->getId()) { - echo $tree->getId() . PHP_EOL; - } + echo $tree->getId() . ' '; foreach ($tree->getChildren() as $child) { static::DFSRecursive($child); } @@ -53,7 +51,7 @@ public static function DFSRecursivePostorder(Tree $tree): void foreach ($tree->getChildren() as $child) { static::DFSRecursivePostorder($child); } - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; } public static function DFSRecursiveInorderBinary(Tree $tree): void @@ -61,15 +59,15 @@ public static function DFSRecursiveInorderBinary(Tree $tree): void switch (count($tree->getChildren())) { case 2: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; static::DFSRecursiveInorderBinary($tree->getChildren()[1]); break; case 1: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; break; case 0: - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; break; default: throw new InvalidArgumentException('Not a binary tree!'); @@ -83,7 +81,7 @@ public static function DFSStack(Tree $tree): void $temp = null; while (null !== ($temp = array_pop($stack))) { - echo $temp->getId() . PHP_EOL; + echo $temp->getId() . ' '; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -96,7 +94,7 @@ public static function DFSQueue(Tree $tree): void $temp = null; while (null !== ($temp = array_shift($stack))) { - echo $temp->getId() . PHP_EOL; + echo $temp->getId() . ' '; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -104,16 +102,13 @@ public static function DFSQueue(Tree $tree): void } } -function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree +function generate_tree(int $numOfRows, int $numOfChildren): Tree { - if ($id === -1) { - $id = 1; - } - $node = new Tree($id); + $node = new Tree($numOfRows); - if ($numOfRows > 1) { + if ($numOfRows > 0) { for ($i = 0; $i < $numOfChildren; $i++) { - $child = generate_tree($numOfRows - 1, $numOfChildren, $id * 10 + $i + 1); + $child = generate_tree($numOfRows - 1, $numOfChildren); $node->addChild($child); } } @@ -121,23 +116,28 @@ function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree return $node; } -$node = generate_tree(3, 3); +$node = generate_tree(2, 3); -echo 'DFS Recursive:' . PHP_EOL; +echo '[#] Recursive DFS:' . PHP_EOL; TreeTraversal::DFSRecursive($node); +echo PHP_EOL; -echo 'DFS Recursive Postorder:' . PHP_EOL; +echo '[#] Recursive Postorder DFS:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); +echo PHP_EOL; -echo 'DFS Stack:' . PHP_EOL; +echo '[#] Stack-based DFS:' . PHP_EOL; TreeTraversal::DFSStack($node); +echo PHP_EOL; -echo 'DFS Queue:' . PHP_EOL; +echo '[#] Queue-based BFS:' . PHP_EOL; TreeTraversal::DFSQueue($node); +echo PHP_EOL; // If you want to try to run binary order on a non-binary tree, // comment out the generation of the new tree below. // If you do that, an exception will be thrown $node = generate_tree(3, 2); -echo 'DFS Recursive Inorder Binary:' . PHP_EOL; +echo '[#] Recursive Inorder DFS for Binary Tree:' . PHP_EOL; TreeTraversal::DFSRecursiveInorderBinary($node); +echo PHP_EOL; From 5396b94dc25438e5af7cf97a5f1458d0900f83a8 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 12:14:47 +0530 Subject: [PATCH 15/90] standardize swift output --- contents/tree_traversal/code/swift/tree.swift | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/contents/tree_traversal/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index e286c8fb0..86e561435 100644 --- a/contents/tree_traversal/code/swift/tree.swift +++ b/contents/tree_traversal/code/swift/tree.swift @@ -22,7 +22,7 @@ func createTree(numRows: Int, numChildren: Int) -> Node { } func dfsRecursive(node: Node) { - print(node.value) + print(node.value, terminator:" ") for child in node.children! { dfsRecursive(node: child) @@ -34,19 +34,19 @@ func dfsRecursivePostOrder(node: Node) { dfsRecursivePostOrder(node: child) } - print(node.value) + print(node.value, terminator:" ") } func dfsRecursiveInOrderBinary(node: Node) { if node.children?.count == 2 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value) + print(node.value, terminator:" ") dfsRecursiveInOrderBinary(node: node.children![1]) } else if node.children?.count == 1 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value) + print(node.value, terminator:" ") } else if node.children?.count == 0 { - print(node.value) + print(node.value, terminator:" ") } else { print("Not a binary tree!") } @@ -58,7 +58,7 @@ func dfsStack(node: Node) { while stack.count > 0 { temp = stack.popLast()! - print(temp.value) + print(temp.value, terminator:" ") for child in temp.children! { stack.append(child) @@ -72,7 +72,7 @@ func bfsQueue(node: Node) { while queue.count > 0 { temp = queue.remove(at: 0) - print(temp.value) + print(temp.value, terminator:" ") for child in temp.children! { queue.append(child) @@ -81,24 +81,29 @@ func bfsQueue(node: Node) { } func main() { - let root = createTree(numRows: 3, numChildren: 3) + let root = createTree(numRows: 2, numChildren: 3) - print("Using recursive DFS:") + print("[#] Recursive DFS:") dfsRecursive(node: root) + print() - print("Using recursive postorder DFS:") + print("[#] Recursive Postorder DFS:") dfsRecursivePostOrder(node: root) + print() - print("Using stack-based DFS:") + print("[#] Stack-based DFS:") dfsStack(node: root) + print() - print("Using queue-based BFS:") + print("[#] Queue-based BFS:") bfsQueue(node: root) + print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("Using In-order DFS:") + print("[#] Recursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) + print() } main() From 6726137a7bf779c5c87a5a12e191cc28cae3771d Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Sat, 4 Sep 2021 20:57:49 +0200 Subject: [PATCH 16/90] removed outdated comments in Coconut implementation --- contents/tree_traversal/code/coconut/tree_traversal.coco | 5 ----- 1 file changed, 5 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index ad7be7932..228d4aab7 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -61,22 +61,18 @@ if __name__ =='__main__': # A ternary tree for testing tree = create_tree(2, 3) - # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Recursive DFS:") dfs_recursive(tree) print() - # Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) print() - # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Stack-based DFS:") dfs_stack(tree) print() - # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 print("[#] Queue-based BFS:") bfs_queue(tree) print() @@ -84,7 +80,6 @@ if __name__ =='__main__': # And a binary tree for testing binary_tree = create_tree(3, 2) - # Should print: 1 2 1 3 1 2 1 print("[#] Recursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From 78246c3104440e79d8c40e4bcf40b51115649e69 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Gillet?= Date: Mon, 6 Sep 2021 10:10:32 +0900 Subject: [PATCH 17/90] standardize haskell output --- .../code/haskell/TreeTraversal.hs | 47 +++++++++---------- contents/tree_traversal/tree_traversal.md | 10 ++-- 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/contents/tree_traversal/code/haskell/TreeTraversal.hs b/contents/tree_traversal/code/haskell/TreeTraversal.hs index 389dc0900..e851f1833 100644 --- a/contents/tree_traversal/code/haskell/TreeTraversal.hs +++ b/contents/tree_traversal/code/haskell/TreeTraversal.hs @@ -1,7 +1,8 @@ data Tree a = Node - { node :: a - , forest :: [Tree a] - } deriving (Show) + { node :: a, + forest :: [Tree a] + } + deriving (Show) dfs :: Tree a -> [a] dfs (Node x ts) = x : concatMap dfs ts @@ -19,7 +20,7 @@ dfsStack :: Tree a -> [a] dfsStack t = go [t] where go [] = [] - go ((Node x ts):stack) = x : go (ts ++ stack) + go ((Node x ts) : stack) = x : go (ts ++ stack) bfs :: Tree a -> [a] bfs (Node x ts) = x : go ts @@ -27,26 +28,22 @@ bfs (Node x ts) = x : go ts go [] = [] go ts = map node ts ++ go (concatMap forest ts) -toBin :: Tree a -> Tree a -toBin (Node x ts) = Node x (map toBin $ take 2 ts) +createTree :: Int -> Int -> Tree Int +createTree 0 _ = Node 0 [] +createTree numRow numChild = Node numRow children + where + children = map (createTree (numRow - 1)) $ replicate numChild numChild main = do - print $ dfs testTree - print $ dfsPostOrder testTree - print $ dfsInOrder $ toBin testTree - print $ dfsStack testTree - print $ bfs testTree - -testTree :: Tree Int -testTree = - Node - 1 - [ Node 2 [Node 3 [], Node 4 [Node 5 []]] - , Node - 6 - [ Node 7 [] - , Node 8 [Node 9 [Node 10 [Node 11 []], Node 12 []]] - , Node 13 [Node 14 []] - ] - , Node 15 [] - ] + let testTree = createTree 2 3 + showNodes = unwords . map show + putStrLn "[#] Recursive DFS:" + putStrLn $ showNodes $ dfs testTree + putStrLn "[#] Recursive Postorder DFS:" + putStrLn $ showNodes $ dfsPostOrder testTree + putStrLn "[#] Stack-based DFS:" + putStrLn $ showNodes $ dfsStack testTree + putStrLn "[#] Queue-based BFS:" + putStrLn $ showNodes $ bfs testTree + putStrLn "[#] Recursive Inorder DFS for Binary Tree:" + putStrLn $ showNodes $ dfsInOrder $ createTree 3 2 diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index 3cc5a2fbb..83c8c8996 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -70,7 +70,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="rs" %} [import:9-15 lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:6-7, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:7-8, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:24-30, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -124,7 +124,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="rs" %} [import:17-24, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:9-10, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:10-11, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:32-38, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -173,7 +173,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="rs" %} [import:25-40, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:12-16, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:13-17, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:40-53, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -231,7 +231,7 @@ In code, it looks like this: {% sample lang="rs" %} [import:41-48, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:18-22, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:19-23, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:55-67, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -282,7 +282,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="rs" %} [import:50-58, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:24-28, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:25-29, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:69-81, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} From 84e60b2e7cf64b7b59ea1d0765a5b4de8810cd8e Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Mon, 6 Sep 2021 18:03:21 +0200 Subject: [PATCH 18/90] Fix asm exit codes (#858) --- contents/monte_carlo_integration/code/asm-x64/monte_carlo.s | 1 + contents/verlet_integration/code/asm-x64/verlet.s | 1 + 2 files changed, 2 insertions(+) diff --git a/contents/monte_carlo_integration/code/asm-x64/monte_carlo.s b/contents/monte_carlo_integration/code/asm-x64/monte_carlo.s index 61355cc95..4fb6d93aa 100644 --- a/contents/monte_carlo_integration/code/asm-x64/monte_carlo.s +++ b/contents/monte_carlo_integration/code/asm-x64/monte_carlo.s @@ -84,5 +84,6 @@ main: call printf add rsp, 16 pop rbp + xor rax, rax # Set exit code to 0 ret diff --git a/contents/verlet_integration/code/asm-x64/verlet.s b/contents/verlet_integration/code/asm-x64/verlet.s index d9617fe33..0e0d031b3 100644 --- a/contents/verlet_integration/code/asm-x64/verlet.s +++ b/contents/verlet_integration/code/asm-x64/verlet.s @@ -124,5 +124,6 @@ main: mov rax, 1 call printf pop rbp + xor rax, rax # Set exit code to 0 ret From 387e43740de8f82d2735a92bdd96c6311b2b67a8 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Mon, 6 Sep 2021 22:12:17 +0530 Subject: [PATCH 19/90] standardize crystal output --- .../code/crystal/tree-traversal.cr | 50 +++++-------------- 1 file changed, 12 insertions(+), 38 deletions(-) diff --git a/contents/tree_traversal/code/crystal/tree-traversal.cr b/contents/tree_traversal/code/crystal/tree-traversal.cr index e3556d8eb..dcd92773b 100644 --- a/contents/tree_traversal/code/crystal/tree-traversal.cr +++ b/contents/tree_traversal/code/crystal/tree-traversal.cr @@ -5,26 +5,26 @@ class Node end def dfs_recursive(node) - print node.id + print "#{node.id} " node.children.each{ |child| dfs_recursive child } end def dfs_recursive_postorder(node) node.children.each{ |child| dfs_recursive_postorder child } - print node.id + print "#{node.id} " end def dfs_recursive_inorder_btree(node) case node.children.size when 2 dfs_recursive_inorder_btree node.children[0] - print node.id + print "#{node.id} " dfs_recursive_inorder_btree node.children[1] when 1 dfs_recursive_inorder_btree node.children[0] - print node.id + print "#{node.id} " when 0 - print node.id + print "#{node.id} " else print "Not a binary tree!" end @@ -35,7 +35,7 @@ def dfs_stack(node) until stack.empty? temp = stack.pop - print temp.id + print "#{temp.id} " temp.children.each{ |child| stack.push child } end end @@ -45,7 +45,7 @@ def bfs_queue(node) until queue.empty? temp = queue.shift - print temp.id + print "#{temp.id} " temp.children.each{ |child| queue.push child } end end @@ -60,54 +60,28 @@ def create_tree(levels, num_childs) Node.new(levels, children) end -def print_tree(node, depth = [] of String) - puts "(#{node.id})" - depth.push " " - len = node.children.size - 1 - - (0 .. len).each do |i| - depth.each{|c| print c} - unless i == len - print "├" - depth.push "│" - print_tree node.children[i], depth - depth.pop - else - print "└" - depth.push " " - print_tree node.children[i], depth - depth.pop - end - end - depth.pop -end - def main - puts "Creating Tree" root = create_tree levels: 2, num_childs: 3 - print_tree root - puts "Using recursive DFS:" + puts "[#] Recursive DFS:" dfs_recursive root puts - puts "Using recursive DFS with post-order traversal:" + puts "[#] Recursive Postorder DFS:" dfs_recursive_postorder root puts - puts "Using stack-based DFS:" + puts "[#] Stack-based DFS:" dfs_stack root puts - puts "Using queue-based BFS:" + puts "[#] Queue-based BFS:" bfs_queue root puts - puts "Creating binary tree to test in-order traversal" root_bin = create_tree levels: 3, num_childs: 2 - print_tree root_bin - puts "Using In-order DFS:" + puts "[#] Recursive Inorder DFS for Binary Tree:" dfs_recursive_inorder_btree root_bin puts end From 09168eb6e59edb06bba87b553843a2163e409ff1 Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Mon, 6 Sep 2021 20:38:55 +0200 Subject: [PATCH 20/90] Flood fill in Coconut (#836) --- .../flood_fill/code/coconut/flood_fill.coco | 113 ++++++++++++++++++ contents/flood_fill/flood_fill.md | 10 ++ 2 files changed, 123 insertions(+) create mode 100644 contents/flood_fill/code/coconut/flood_fill.coco diff --git a/contents/flood_fill/code/coconut/flood_fill.coco b/contents/flood_fill/code/coconut/flood_fill.coco new file mode 100644 index 000000000..f2580a608 --- /dev/null +++ b/contents/flood_fill/code/coconut/flood_fill.coco @@ -0,0 +1,113 @@ +from collections import deque +import numpy as np + + +data Point(x, y): + def __add__(self, other is Point) = Point(self.x + other.x, self.y + other.y) + + +# This function is necessary, because negative indices wrap around the +# array in Coconut. +def inbounds(canvas_shape, location is Point) = + min(location) >= 0 and location.x < canvas_shape[0] and location.y < canvas_shape[1] + + +def find_neighbours(canvas, location is Point, old_value): + possible_neighbours = ((Point(0, 1), Point(1, 0), Point(0, -1), Point(-1, 0)) + |> map$(location.__add__)) + + yield from possible_neighbours |> filter$(x -> (inbounds(canvas.shape, x) + and canvas[x] == old_value)) + + +def stack_fill(canvas, location is Point, old_value, new_value): + if new_value == old_value or not inbounds(canvas.shape, location): + return + + stack = [location] + + while stack: + current_location = stack.pop() + if canvas[current_location] == old_value: + canvas[current_location] = new_value + stack.extend(find_neighbours(canvas, current_location, old_value)) + + +def queue_fill(canvas, location is Point, old_value, new_value): + if new_value == old_value or not inbounds(canvas.shape, location): + return + + queue = deque() + queue.append(location) + + canvas[location] = new_value + + while queue: + current_location = queue.popleft() + for neighbour in find_neighbours(canvas, current_location, old_value): + canvas[neighbour] = new_value + queue.append(neighbour) + + +def recursive_fill(canvas, location is Point, old_value, new_value): + if new_value == old_value or not inbounds(canvas.shape, location): + return + + canvas[location] = new_value + # consume is important here, because otherwise, the recursive function is not called again + consume( + find_neighbours(canvas, location, old_value) + |> map$(recursive_fill$(canvas, ?, old_value, new_value)) + ) + + +def test_grid(initial_canvas, final_canvas, function): + canvas = initial_canvas.copy() # ensure the initial_canvas is unchanged + function(canvas) + return (canvas == final_canvas).all() + +def test(): + from collections import namedtuple + + TestResults = namedtuple('TestResults', 'passes failures') + pass_count = failure_count = 0 + + grid = np.zeros((5, 5)) + grid[2,:] = 1 + solution_grid = np.zeros((5, 5)) + solution_grid[:3,] = 1 + + starting_location = Point(0, 0) + + recursive_test_func = recursive_fill$(?, starting_location, 0, 1) + # The following is manual unit testing of the function + if test_grid(grid, solution_grid, recursive_test_func): + pass_count += 1 + print('.', end='') + else: + failure_count += 1 + print('F', end='') + + stack_test_func = stack_fill$(?, starting_location, 0, 1) + if test_grid(grid, solution_grid, stack_test_func): + print('.', end='') + pass_count += 1 + else: + print('F', end='') + failure_count += 1 + + queue_test_func = queue_fill$(?, starting_location, 0, 1) + if test_grid(grid, solution_grid, queue_test_func): + print('.', end='') + pass_count += 1 + else: + print('F', end='') + failure_count += 1 + + print() + print(TestResults(pass_count, failure_count)) + +if __name__ == '__main__': + # Testing setup + test() + diff --git a/contents/flood_fill/flood_fill.md b/contents/flood_fill/flood_fill.md index 87ec2b7a7..185050fe1 100644 --- a/contents/flood_fill/flood_fill.md +++ b/contents/flood_fill/flood_fill.md @@ -92,6 +92,8 @@ In code, this might look like this: [import:28-46, lang:"c"](code/c/flood_fill.c) {% sample lang="py" %} [import:10-25, lang="python"](code/python/flood_fill.py) +{% sample lang="coco" %} +[import:15-19, lang="coconut"](code/coconut/flood_fill.coco) {% endmethod %} @@ -110,6 +112,8 @@ In code, it might look like this: [import:174-189, lang:"c"](code/c/flood_fill.c) {% sample lang="py" %} [import:55-63, lang="python"](code/python/flood_fill.py) +{% sample lang="coco" %} +[import:54-63, lang:"coconut"](code/coconut/flood_fill.coco) {% endmethod %} The above code continues recursing through available neighbors as long as neighbors exist, and this should work so long as we are adding the correct set of neighbors. @@ -123,6 +127,8 @@ Additionally, it is possible to do the same type of traversal by managing a stac [import:79-102, lang:"c"](code/c/flood_fill.c) {% sample lang="py" %} [import:27-36, lang="python"](code/python/flood_fill.py) +{% sample lang="coco" %} +[import:23-34, lang:"coconut"](code/coconut/flood_fill.coco) {% endmethod %} This is ultimately the same method of traversal as before; however, because we are managing our own data structure, there are a few distinct differences: @@ -164,6 +170,8 @@ The code would look something like this: [import:149-172, lang:"c"](code/c/flood_fill.c) {% sample lang="py" %} [import:38-53, lang="python"](code/python/flood_fill.py) +{% sample lang="coco" %} +[import:37-51, lang:"coconut"](code/coconut/flood_fill.coco) {% endmethod %} Now, there is a small trick in this code that must be considered to make sure it runs optimally. @@ -244,6 +252,8 @@ After, we will fill in the left-hand side of the array to be all ones by choosin [import, lang:"c"](code/c/flood_fill.c) {% sample lang="py" %} [import:, lang="python"](code/python/flood_fill.py) +{% sample lang="coco" %} +[import, lang="coconut"](code/coconut/flood_fill.coco) {% endmethod %} From bd588627845b7e1e80d226e1cb78118e4e961dee Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Mon, 6 Sep 2021 21:22:03 +0200 Subject: [PATCH 21/90] Added Barnsley fern in Coconut (+ .editorconfig for Coconut) (#814) --- .editorconfig | 3 ++ contents/barnsley/barnsley.md | 5 ++- contents/barnsley/code/coconut/barnsley.coco | 44 ++++++++++++++++++++ 3 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 contents/barnsley/code/coconut/barnsley.coco diff --git a/.editorconfig b/.editorconfig index 4ea5e2ea9..a3fbd6e02 100644 --- a/.editorconfig +++ b/.editorconfig @@ -172,3 +172,6 @@ indent_size = 4 indent_style = space indent_size = 2 +[*.coco] +indent_style = space +indent_size = 4 diff --git a/contents/barnsley/barnsley.md b/contents/barnsley/barnsley.md index 0c0cf682b..e3f01f96f 100644 --- a/contents/barnsley/barnsley.md +++ b/contents/barnsley/barnsley.md @@ -85,7 +85,7 @@ To account for this, each function is also given a probability of being chosen: | Function | Probability | | -------- | ----------- | | $$f_1(P) = \begin{bmatrix} 0 &0 \\ 0 &0.16 \end{bmatrix}P + \begin{bmatrix} 0 \\ 0 \end{bmatrix}$$ | 0.01 | -| $$f_2(P) = \begin{bmatrix} 0.85 &0.04 \\ -0.04 &0.85 \end{bmatrix}P + \begin{bmatrix} 0 \\ 1.6 \end{bmatrix}$$ | 0.85 | +| $$f_2(P) = \begin{bmatrix} 0.85 &0.04 \\ -0.04 &0.85 \end{bmatrix}P + \begin{bmatrix} 0 \\ 1.6 \end{bmatrix}$$ | 0.85 | | $$f_3(P) = \begin{bmatrix} 0.2 &-0.26 \\ 0.23 &022 \end{bmatrix}P + \begin{bmatrix} 0 \\ 1.6 \end{bmatrix}$$ | 0.07 | | $$f_4(P) = \begin{bmatrix} -0.15 &0.28 \\ 0.26 &0.24 \end{bmatrix}P + \begin{bmatrix} 0 \\ 0.44 \end{bmatrix}$$ | 0.07 | @@ -131,6 +131,9 @@ The biggest differences between the two code implementations is that the Barnsle [import, lang:"c"](code/c/barnsley.c) {% sample lang="java" %} [import, lang:"java"](code/java/Barnsley.java) +{% sample lang="coco" %} +[import, lang:"coconut"](code/julia/barnsley.coco) + {% endmethod %} ### Bibliography diff --git a/contents/barnsley/code/coconut/barnsley.coco b/contents/barnsley/code/coconut/barnsley.coco new file mode 100644 index 000000000..a27fc7c5c --- /dev/null +++ b/contents/barnsley/code/coconut/barnsley.coco @@ -0,0 +1,44 @@ +from random import choices +import numpy as np + +data Point(x=0, y=0): + def __rmatmul__(self, mat: np.array): + point_array = np.array([self.x, self.y, 1]) + x, y, *_ = tuple(*(mat @ point_array)) + return Point(x, y) + + +def chaos_game(initial_location is Point, hutchinson_op, probabilities): + point = initial_location + while True: + yield (point := choices(hutchinson_op, probabilities) @ point) + +barnsley_hutchinson = [ + np.array([ + [0., 0., 0.], + [0., 0.16, 0.], + [0., 0., 1.], + ]), + np.array([ + [0.85, 0.04, 0.], + [-0.04, 0.85, 1.6], + [0., 0., 1.], + ]), + np.array([ + [0.2, -0.26, 0.], + [0.23, 0.22, 1.6], + [0., 0., 1.], + ]), + np.array([ + [-0.15, 0.28, 0.], + [0.26, 0.24, 0.44], + [0., 0., 1.], + ]), +] + +barnsley_probabilities = [0.01, 0.85, 0.07, 0.07] + +if __name__ == '__main__': + output_gen = chaos_game(Point(0, 0), barnsley_hutchinson, barnsley_probabilities) + output_points = np.array([*output_gen$[:10000]]) + np.savetxt("out.dat", output_points) From cc457b95522ed92d92c0181ba96d497fc6a972df Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Mon, 6 Sep 2021 23:49:37 +0200 Subject: [PATCH 22/90] Added the Jarvis march in Coconut (#734) --- .../code/coconut/jarvis_march.coco | 40 +++++++++++++++++++ contents/jarvis_march/jarvis_march.md | 2 + 2 files changed, 42 insertions(+) create mode 100644 contents/jarvis_march/code/coconut/jarvis_march.coco diff --git a/contents/jarvis_march/code/coconut/jarvis_march.coco b/contents/jarvis_march/code/coconut/jarvis_march.coco new file mode 100644 index 000000000..f54aa4336 --- /dev/null +++ b/contents/jarvis_march/code/coconut/jarvis_march.coco @@ -0,0 +1,40 @@ +data point(x=0, y=0): + def __str__(self): + return f'({self.x}, {self.y})' + +# Is the turn counter-clockwise? +def counter_clockwise(p1 is point, p2 is point, p3 is point) = + (p3.y - p1.y) * (p2.x - p1.x) >= (p2.y - p1.y) * (p3.x - p1.x) + + +def jarvis_march(gift: point[]) -> point[]: + point_on_hull = min(gift) # The leftmost point in the gift + hull = [point_on_hull] # It is guaranteed it will be on the hull. + + while True: + # Candidate for the next point in the hull + endpoint = gift[0] + for p in gift: + if (endpoint == point_on_hull + or not counter_clockwise(p, hull[-1], endpoint)): + endpoint = p + + point_on_hull = endpoint + + # Check if the gift is completely covered. + if hull[0] == endpoint: + return hull + hull.append(point_on_hull) + + +if __name__ == '__main__': + test_gift = [ + (-5, 2), (5, 7), (-6, -12), (-14, -14), (9, 9), + (-1, -1), (-10, 11), (-6, 15), (-6, -8), (15, -9), + (7, -7), (-2, -9), (6, -5), (0, 14), (2, 8) + ] |> map$(t -> point(*t)) |> list + hull = jarvis_march(test_gift) + + print("[#] The points in the hull are:") + for point in hull: + print(point) diff --git a/contents/jarvis_march/jarvis_march.md b/contents/jarvis_march/jarvis_march.md index 0a48dbd85..fa244713e 100644 --- a/contents/jarvis_march/jarvis_march.md +++ b/contents/jarvis_march/jarvis_march.md @@ -50,6 +50,8 @@ Since this algorithm, there have been many other algorithms that have advanced t [import, lang:"v"](code/v/jarvis.v) {% sample lang="rust" %} [import, lang:"rust"](code/rust/jarvis_march.rs) +{% sample lang="coco" %} +[import, lang:"coconut"](code/coconut/jarvis_march.coco) {% endmethod %} @@ -54,6 +63,11 @@ MathJax.Hub.Queue(["Typeset",MathJax.Hub]); The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/master/LICENSE.md)). +##### Images/Graphics + +- The image "[Cyclic](../res/cyclic.png)" was created by [James Schloss](https://github.com/leios) and is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/legalcode). + + ##### Text The text of this chapter was written by [James Schloss](https://github.com/leios) and is licensed under the [Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/legalcode). From 46bf5a378ae875c56369cdaa8da7b93c4f0e7ce4 Mon Sep 17 00:00:00 2001 From: Ayman Lafaz Date: Sun, 10 Oct 2021 15:15:43 +0100 Subject: [PATCH 43/90] added convolutional theorem implementation in python (#869) * added convolutional theorem implementation in python * fixed chapter linking * added comments to the code * changed random distribution to sawtooth * corrected previous commit * fixed comments Co-authored-by: James Schloss --- .../code/python/convolutional_theorem.py | 19 +++++++++++++++++++ .../convolutional_theorem.md | 3 ++- 2 files changed, 21 insertions(+), 1 deletion(-) create mode 100644 contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py diff --git a/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py b/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py new file mode 100644 index 000000000..f64f44a1d --- /dev/null +++ b/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py @@ -0,0 +1,19 @@ +from scipy.fft import fft, ifft +import numpy as np + +# using the convolutional theorem +def convolve_fft(signal1, signal2): + return ifft(np.multiply(fft(signal1),fft(signal2))) + +# Sawtooth functions +x = [float(i)/200 for i in range(1,101)] +y = [float(i)/200 for i in range(1,101)] + +x /= np.linalg.norm(x) +y /= np.linalg.norm(y) + +# Convolving the two signals +fft_output = convolve_fft(x, y) + +np.savetxt("fft.dat", np.real(fft_output)) + diff --git a/contents/convolutions/convolutional_theorem/convolutional_theorem.md b/contents/convolutions/convolutional_theorem/convolutional_theorem.md index 7aa5c3fdf..1034f2018 100644 --- a/contents/convolutions/convolutional_theorem/convolutional_theorem.md +++ b/contents/convolutions/convolutional_theorem/convolutional_theorem.md @@ -44,6 +44,8 @@ For this example code, we will be using two sawtooth functions as we did in the {% method %} {% sample lang="jl" %} [import, lang:"julia"](code/julia/convolutional_theorem.jl) +{% sample lang="py" %} +[import, lang:"python"](code/python/convolutional_theorem.py) {% endmethod %} This should produce the following output: @@ -52,7 +54,6 @@ This should produce the following output:

- From 39f8c1c11b9066aa8b5a156f17c47979381490ce Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Sun, 10 Oct 2021 16:28:38 +0200 Subject: [PATCH 44/90] Use `[#]\n` instead of `[#]` for human readable output (#873) --- contents/verlet_integration/code/asm-x64/verlet.s | 6 +++--- contents/verlet_integration/code/c++/verlet.cpp | 10 +++++----- contents/verlet_integration/code/c/verlet.c | 10 +++++----- .../verlet_integration/code/clisp/verlet.lisp | 10 +++++----- .../verlet_integration/code/fortran/verlet.f90 | 15 ++++++++++----- contents/verlet_integration/code/golang/verlet.go | 10 +++++----- .../verlet_integration/code/haskell/verlet.hs | 10 +++++----- contents/verlet_integration/code/java/Verlet.java | 10 +++++----- .../verlet_integration/code/javascript/verlet.js | 10 +++++----- contents/verlet_integration/code/julia/verlet.jl | 10 +++++----- contents/verlet_integration/code/kotlin/verlet.kt | 10 +++++----- contents/verlet_integration/code/nim/verlet.nim | 10 +++++----- contents/verlet_integration/code/python/verlet.py | 10 +++++----- contents/verlet_integration/code/ruby/verlet.rb | 10 +++++----- contents/verlet_integration/code/rust/verlet.rs | 10 +++++----- .../verlet_integration/code/swift/verlet.swift | 10 +++++----- 16 files changed, 83 insertions(+), 78 deletions(-) diff --git a/contents/verlet_integration/code/asm-x64/verlet.s b/contents/verlet_integration/code/asm-x64/verlet.s index 0e0d031b3..87de6cb7a 100644 --- a/contents/verlet_integration/code/asm-x64/verlet.s +++ b/contents/verlet_integration/code/asm-x64/verlet.s @@ -4,9 +4,9 @@ zero: .double 0.0 two: .double 2.0 half: .double 0.5 - verlet_fmt: .string "[#] Time for Verlet integration is:\n%lf\n" - stormer_fmt: .string "[#] Time for Stormer Verlet Integration is:\n%lf\n[#] Velocity for Stormer Verlet Integration is:\n%lf\n" - velocity_fmt: .string "[#] Time for Velocity Verlet Integration is:\n%lf\n[#] Velocity for Velocity Verlet Integration is:\n%lf\n" + verlet_fmt: .string "[#]\nTime for Verlet integration is:\n%lf\n" + stormer_fmt: .string "[#]\nTime for Stormer Verlet Integration is:\n%lf\n[#]\nVelocity for Stormer Verlet Integration is:\n%lf\n" + velocity_fmt: .string "[#]\nTime for Velocity Verlet Integration is:\n%lf\n[#]\nVelocity for Velocity Verlet Integration is:\n%lf\n" pos: .double 5.0 acc: .double -10.0 dt: .double 0.01 diff --git a/contents/verlet_integration/code/c++/verlet.cpp b/contents/verlet_integration/code/c++/verlet.cpp index 946ddc618..ccceb0ff3 100644 --- a/contents/verlet_integration/code/c++/verlet.cpp +++ b/contents/verlet_integration/code/c++/verlet.cpp @@ -64,19 +64,19 @@ int main() { // each of these functions. double time = verlet(5.0, -10, 0.01); - std::cout << "[#] Time for Verlet integration is:\n" \ + std::cout << "[#]\nTime for Verlet integration is:\n" \ << time << std::endl; timestep timestep_sv = stormer_verlet(5.0, -10, 0.01); - std::cout << "[#] Time for Stormer Verlet integration is:\n" \ + std::cout << "[#]\nTime for Stormer Verlet integration is:\n" \ << timestep_sv.time << std::endl; - std::cout << "[#] Velocity for Stormer Verlet integration is:\n" \ + std::cout << "[#]\nVelocity for Stormer Verlet integration is:\n" \ << timestep_sv.vel << std::endl; timestep timestep_vv = velocity_verlet(5.0, -10, 0.01); - std::cout << "[#] Time for velocity Verlet integration is:\n" \ + std::cout << "[#]\nTime for velocity Verlet integration is:\n" \ << timestep_vv.time << std::endl; - std::cout << "[#] Velocity for velocity Verlet integration is:\n" \ + std::cout << "[#]\nVelocity for velocity Verlet integration is:\n" \ << timestep_vv.vel << std::endl; return 0; diff --git a/contents/verlet_integration/code/c/verlet.c b/contents/verlet_integration/code/c/verlet.c index c42254974..a5febb92c 100644 --- a/contents/verlet_integration/code/c/verlet.c +++ b/contents/verlet_integration/code/c/verlet.c @@ -46,19 +46,19 @@ int main() { double time, vel; verlet(&time, 5.0, -10, 0.01); - printf("[#] Time for Verlet integration is:\n"); + printf("[#]\nTime for Verlet integration is:\n"); printf("%lf\n", time); stormer_verlet(&time, &vel, 5.0, -10, 0.01); - printf("[#] Time for Stormer Verlet integration is:\n"); + printf("[#]\nTime for Stormer Verlet integration is:\n"); printf("%lf\n", time); - printf("[#] Velocity for Stormer Verlet integration is:\n"); + printf("[#]\nVelocity for Stormer Verlet integration is:\n"); printf("%lf\n", vel); velocity_verlet(&time, &vel, 5.0, -10, 0.01); - printf("[#] Time for velocity Verlet integration is:\n"); + printf("[#]\nTime for velocity Verlet integration is:\n"); printf("%lf\n", time); - printf("[#] Velocity for Stormer Verlet integration is:\n"); + printf("[#]\nVelocity for Stormer Verlet integration is:\n"); printf("%lf\n", vel); return 0; diff --git a/contents/verlet_integration/code/clisp/verlet.lisp b/contents/verlet_integration/code/clisp/verlet.lisp index f08f2a7e6..f8d4c6c14 100644 --- a/contents/verlet_integration/code/clisp/verlet.lisp +++ b/contents/verlet_integration/code/clisp/verlet.lisp @@ -34,17 +34,17 @@ while (> p 0) finally (return (list time vel)))) -(format T "[#] Time for Verlet integration:~%") +(format T "[#]~%Time for Verlet integration:~%") (format T "~d~%" (verlet 5 -10 0.01)) (defvar stormer-verlet-result (stormer-verlet 5 -10 0.01)) -(format T "[#] Time for Stormer Verlet integration is:~%") +(format T "[#]~%Time for Stormer Verlet integration is:~%") (format T "~d~%" (first stormer-verlet-result)) -(format T "[#] Velocity for Stormer Verlet integration is:~%") +(format T "[#]~%Velocity for Stormer Verlet integration is:~%") (format T "~d~%" (second stormer-verlet-result)) (defvar velocity-verlet-result (velocity-verlet 5 -10 0.01)) -(format T "[#] Time for velocity Verlet integration is:~%") +(format T "[#]~%Time for velocity Verlet integration is:~%") (format T "~d~%" (first velocity-verlet-result)) -(format T "[#] Velocity for velocity Verlet integration is:~%") +(format T "[#]~%Velocity for velocity Verlet integration is:~%") (format T "~d~%" (second velocity-verlet-result)) \ No newline at end of file diff --git a/contents/verlet_integration/code/fortran/verlet.f90 b/contents/verlet_integration/code/fortran/verlet.f90 index 6999df1e5..3fda9f950 100644 --- a/contents/verlet_integration/code/fortran/verlet.f90 +++ b/contents/verlet_integration/code/fortran/verlet.f90 @@ -91,16 +91,19 @@ SUBROUTINE velocity_verlet(pos, acc, dt, time, vel) ! Verlet CALL verlet(pos, acc, dt, time) - WRITE(*,*) '[#] Time for Verlet integration:' + WRITE(*,*) '[#]' + WRITE(*,*) 'Time for Verlet integration:' WRITE(*,*) time ! stormer Verlet pos = 5d0 CALL stormer_verlet(pos, acc, dt, time, vel) - WRITE(*,*) '[#] Time for Stormer Verlet integration:' + WRITE(*,*) '[#]' + WRITE(*,*) 'Time for Stormer Verlet integration:' WRITE(*,*) time - WRITE(*,*) '[#] Velocity for Stormer Verlet integration:' + WRITE(*,*) '[#]' + WRITE(*,*) 'Velocity for Stormer Verlet integration:' WRITE(*,*) vel @@ -109,9 +112,11 @@ SUBROUTINE velocity_verlet(pos, acc, dt, time, vel) pos = 5d0 CALL velocity_verlet(pos, acc, dt, time, vel) - WRITE(*,*) '[#] Time for velocity Verlet integration:' + WRITE(*,*) '[#]' + WRITE(*,*) 'Time for velocity Verlet integration:' WRITE(*,*) time - WRITE(*,*) '[#] Velocity for velocity Verlet integration:' + WRITE(*,*) '[#]' + WRITE(*,*) 'Velocity for velocity Verlet integration:' WRITE(*,*) vel END PROGRAM verlet_integration diff --git a/contents/verlet_integration/code/golang/verlet.go b/contents/verlet_integration/code/golang/verlet.go index a7cd1c86b..d4fc956a9 100644 --- a/contents/verlet_integration/code/golang/verlet.go +++ b/contents/verlet_integration/code/golang/verlet.go @@ -43,18 +43,18 @@ func velocityVerlet(pos, acc, dt float64) (time, vel float64) { func main() { time := verlet(5., -10., .01) - fmt.Println("[#] Time for Verlet integration is:") + fmt.Println("[#]\nTime for Verlet integration is:") fmt.Println(time) time, vel := stormerVerlet(5., -10., .01) - fmt.Println("[#] Time for Stormer Verlet integration is:") + fmt.Println("[#]\nTime for Stormer Verlet integration is:") fmt.Println(time) - fmt.Println("[#] Velocity for Stormer Verlet integration is:") + fmt.Println("[#]\nVelocity for Stormer Verlet integration is:") fmt.Println(vel) time, vel = velocityVerlet(5., -10., .01) - fmt.Println("[#] Time for velocity Verlet integration is:") + fmt.Println("[#]\nTime for velocity Verlet integration is:") fmt.Println(time) - fmt.Println("[#] Velocity for velocity Verlet integration is:") + fmt.Println("[#]\nVelocity for velocity Verlet integration is:") fmt.Println(vel) } diff --git a/contents/verlet_integration/code/haskell/verlet.hs b/contents/verlet_integration/code/haskell/verlet.hs index 675c7f39b..af964d4d7 100644 --- a/contents/verlet_integration/code/haskell/verlet.hs +++ b/contents/verlet_integration/code/haskell/verlet.hs @@ -52,13 +52,13 @@ main = do let (_, v, _, t) = last $ takeWhile aboveGround $ trajectory m freefall dt p0 in (show t, show v) - putStrLn "[#] Time for Verlet integration is:" + putStrLn "[#]\nTime for Verlet integration is:" putStrLn $ fst $ timeVelocity verlet - putStrLn "[#] Time for Stormer Verlet integration is:" + putStrLn "[#]\nTime for Stormer Verlet integration is:" putStrLn $ fst $ timeVelocity stormerVerlet - putStrLn "[#] Velocity for Stormer Verlet integration is:" + putStrLn "[#]\nVelocity for Stormer Verlet integration is:" putStrLn $ snd $ timeVelocity stormerVerlet - putStrLn "[#] Time for velocity Verlet integration is:" + putStrLn "[#]\nTime for velocity Verlet integration is:" putStrLn $ fst $ timeVelocity velocityVerlet - putStrLn "[#] Velocity for velocity Verlet integration is:" + putStrLn "[#]\nVelocity for velocity Verlet integration is:" putStrLn $ snd $ timeVelocity velocityVerlet diff --git a/contents/verlet_integration/code/java/Verlet.java b/contents/verlet_integration/code/java/Verlet.java index 35387cf8b..38283abed 100644 --- a/contents/verlet_integration/code/java/Verlet.java +++ b/contents/verlet_integration/code/java/Verlet.java @@ -65,19 +65,19 @@ static VerletValues velocity_verlet(double pos, double acc, double dt) { public static void main(String[] args) { double verletTime = verlet(5.0, -10, 0.01); - System.out.println("[#] Time for Verlet integration is:"); + System.out.println("[#]\nTime for Verlet integration is:"); System.out.println(verletTime); VerletValues stormerVerlet = stormer_verlet(5.0, -10, 0.01); - System.out.println("[#] Time for Stormer Verlet integration is:"); + System.out.println("[#]\nTime for Stormer Verlet integration is:"); System.out.println(stormerVerlet.time); - System.out.println("[#] Velocity for Stormer Verlet integration is:"); + System.out.println("[#]\nVelocity for Stormer Verlet integration is:"); System.out.println(stormerVerlet.vel); VerletValues velocityVerlet = velocity_verlet(5.0, -10, 0.01); - System.out.println("[#] Time for velocity Verlet integration is:"); + System.out.println("[#]\nTime for velocity Verlet integration is:"); System.out.println(velocityVerlet.time); - System.out.println("[#] Velocity for velocity Verlet integration is:"); + System.out.println("[#]\nVelocity for velocity Verlet integration is:"); System.out.println(velocityVerlet.vel); } diff --git a/contents/verlet_integration/code/javascript/verlet.js b/contents/verlet_integration/code/javascript/verlet.js index 7ea09e187..d406482d4 100644 --- a/contents/verlet_integration/code/javascript/verlet.js +++ b/contents/verlet_integration/code/javascript/verlet.js @@ -45,17 +45,17 @@ function velocityVerlet(pos, acc, dt) { } const time = verlet(5, -10, 0.01); -console.log(`[#] Time for Verlet integration is:`); +console.log(`[#]\nTime for Verlet integration is:`); console.log(`${time}`); const stormer = stormerVerlet(5, -10, 0.01); -console.log(`[#] Time for Stormer Verlet integration is:`); +console.log(`[#]\nTime for Stormer Verlet integration is:`); console.log(`${stormer.time}`); -console.log(`[#] Velocity for Stormer Verlet integration is:`); +console.log(`[#]\nVelocity for Stormer Verlet integration is:`); console.log(`${stormer.vel}`); const velocity = velocityVerlet(5, -10, 0.01); -console.log(`[#] Time for velocity Verlet integration is:`); +console.log(`[#]\nTime for velocity Verlet integration is:`); console.log(`${velocity.time}`); -console.log(`[#] Velocity for velocity Verlet integration is:`); +console.log(`[#]\nVelocity for velocity Verlet integration is:`); console.log(`${velocity.vel}`); diff --git a/contents/verlet_integration/code/julia/verlet.jl b/contents/verlet_integration/code/julia/verlet.jl index b9edcea98..2d50e5512 100644 --- a/contents/verlet_integration/code/julia/verlet.jl +++ b/contents/verlet_integration/code/julia/verlet.jl @@ -46,19 +46,19 @@ end function main() time = verlet(5.0, -10.0, 0.01); - println("[#] Time for Verlet integration is:") + println("[#]\nTime for Verlet integration is:") println("$(time)") time, vel = stormer_verlet(5.0, -10.0, 0.01); - println("[#] Time for Stormer Verlet integration is:") + println("[#]\nTime for Stormer Verlet integration is:") println("$(time)") - println("[#] Velocity for Stormer Verlet integration is:") + println("[#]\nVelocity for Stormer Verlet integration is:") println("$(vel)") time, vel = velocity_verlet(5.0, -10.0, 0.01); - println("[#] Time for velocity Verlet integration is:") + println("[#]\nTime for velocity Verlet integration is:") println("$(time)") - println("[#] Velocity for velocity Verlet integration is:") + println("[#]\nVelocity for velocity Verlet integration is:") println("$(vel)") end diff --git a/contents/verlet_integration/code/kotlin/verlet.kt b/contents/verlet_integration/code/kotlin/verlet.kt index 79bee7b6a..3b365451c 100644 --- a/contents/verlet_integration/code/kotlin/verlet.kt +++ b/contents/verlet_integration/code/kotlin/verlet.kt @@ -43,18 +43,18 @@ fun velocityVerlet(_pos: Double, acc: Double, dt: Double): VerletValues { fun main(args: Array) { val verletTime = verlet(5.0, -10.0, 0.01) - println("[#] Time for Verlet integration is:") + println("[#]\nTime for Verlet integration is:") println("$verletTime") val stormerVerlet = stormerVerlet(5.0, -10.0, 0.01) - println("[#] Time for Stormer Verlet integration is:") + println("[#]\nTime for Stormer Verlet integration is:") println("${stormerVerlet.time}") - println("[#] Velocity for Stormer Verlet integration is:") + println("[#]\nVelocity for Stormer Verlet integration is:") println("${stormerVerlet.vel}") val velocityVerlet = velocityVerlet(5.0, -10.0, 0.01) - println("[#] Time for Velocity Verlet integration is:") + println("[#]\nTime for Velocity Verlet integration is:") println("${velocityVerlet.time}") - println("[#] Velocity for Velocity Verlet integration is:") + println("[#]\nVelocity for Velocity Verlet integration is:") println("${velocityVerlet.vel}") } diff --git a/contents/verlet_integration/code/nim/verlet.nim b/contents/verlet_integration/code/nim/verlet.nim index 2e92b57c4..ff454b7ee 100644 --- a/contents/verlet_integration/code/nim/verlet.nim +++ b/contents/verlet_integration/code/nim/verlet.nim @@ -46,17 +46,17 @@ func velocityVerlet(pos_in, acc, dt: float): (float, float) = when isMainModule: let timeV = verlet(5.0, -10.0, 0.01) - echo "[#] Time for Verlet integration is:" + echo "[#]\nTime for Verlet integration is:" echo timeV let (timeSV, velSV) = stormerVerlet(5.0, -10.0, 0.01) - echo "[#] Time for Stormer Verlet integration is:" + echo "[#]\nTime for Stormer Verlet integration is:" echo timeSV - echo "[#] Velocity for Stormer Verlet integration is:" + echo "[#]\nVelocity for Stormer Verlet integration is:" echo velSV let (timeVV, velVV) = velocityVerlet(5.0, -10.0, 0.01) - echo "[#] Time for velocity Verlet integration is:" + echo "[#]\nTime for velocity Verlet integration is:" echo timeVV - echo "[#] Velocity for velocity Verlet integration is:" + echo "[#]\nVelocity for velocity Verlet integration is:" echo velVV diff --git a/contents/verlet_integration/code/python/verlet.py b/contents/verlet_integration/code/python/verlet.py index 18dc627d3..063e19666 100644 --- a/contents/verlet_integration/code/python/verlet.py +++ b/contents/verlet_integration/code/python/verlet.py @@ -35,19 +35,19 @@ def velocity_verlet(pos, acc, dt): def main(): time = verlet(5, -10, 0.01) - print("[#] Time for Verlet integration is:") + print("[#]\nTime for Verlet integration is:") print("{:.10f}".format(time)) time, vel = stormer_verlet(5, -10, 0.01) - print("[#] Time for Stormer Verlet integration is:") + print("[#]\nTime for Stormer Verlet integration is:") print("{:.10f}".format(time)) - print("[#] Velocity for Stormer Verlet integration is:") + print("[#]\nVelocity for Stormer Verlet integration is:") print("{:.10f}".format(vel)) time, vel = velocity_verlet(5, -10, 0.01) - print("[#] Time for velocity Verlet integration is:") + print("[#]\nTime for velocity Verlet integration is:") print("{:.10f}".format(time)) - print("[#] Velocity for velocity Verlet integration is:") + print("[#]\nVelocity for velocity Verlet integration is:") print("{:.10f}".format(vel)) diff --git a/contents/verlet_integration/code/ruby/verlet.rb b/contents/verlet_integration/code/ruby/verlet.rb index 4a6c38a48..d11243568 100644 --- a/contents/verlet_integration/code/ruby/verlet.rb +++ b/contents/verlet_integration/code/ruby/verlet.rb @@ -45,17 +45,17 @@ def velocity_verlet(pos, acc, dt) end -puts "[#] Time for Verlet integration is:" +puts "[#]\nTime for Verlet integration is:" p verlet(5.0, -10, 0.01) time, vel = stormer_verlet(5.0, -10, 0.01) -puts "[#] Time for Stormer Verlet integration is:" +puts "[#]\nTime for Stormer Verlet integration is:" p time -puts "[#] Velocity for Stormer Verlet integration is:" +puts "[#]\nVelocity for Stormer Verlet integration is:" p vel time, vel = velocity_verlet(5.0, -10, 0.01) -puts "[#] Time for velocity Verlet integration is:" +puts "[#]\nTime for velocity Verlet integration is:" p time -puts "[#] Velocity for velocity Verlet integration is:" +puts "[#]\nVelocity for velocity Verlet integration is:" p vel diff --git a/contents/verlet_integration/code/rust/verlet.rs b/contents/verlet_integration/code/rust/verlet.rs index f765da864..8901a3790 100644 --- a/contents/verlet_integration/code/rust/verlet.rs +++ b/contents/verlet_integration/code/rust/verlet.rs @@ -49,16 +49,16 @@ fn main() { let (time_sv, vel_sv) = stormer_verlet(5.0, -10.0, 0.01); let (time_vv, vel_vv) = velocity_verlet(5.0, -10.0, 0.01); - println!("[#] Time for Verlet integration is:"); + println!("[#]\nTime for Verlet integration is:"); println!("{}", time_v); - println!("[#] Time for Stormer Verlet integration is:"); + println!("[#]\nTime for Stormer Verlet integration is:"); println!("{}", time_sv); - println!("[#] Velocity for Stormer Verlet integration is:"); + println!("[#]\nVelocity for Stormer Verlet integration is:"); println!("{}", vel_sv); - println!("[#] Time for velocity Verlet integration is:"); + println!("[#]\nTime for velocity Verlet integration is:"); println!("{}", time_vv); - println!("[#] Velocity for velocity Verlet integration is:"); + println!("[#]\nVelocity for velocity Verlet integration is:"); println!("{}", vel_vv); } diff --git a/contents/verlet_integration/code/swift/verlet.swift b/contents/verlet_integration/code/swift/verlet.swift index 7991a0082..f7d1973bc 100644 --- a/contents/verlet_integration/code/swift/verlet.swift +++ b/contents/verlet_integration/code/swift/verlet.swift @@ -50,19 +50,19 @@ func velocityVerlet(pos: Double, acc: Double, dt: Double) -> (time: Double, vel: func main() { let verletTime = verlet(pos: 5.0, acc: -10.0, dt: 0.01) - print("[#] Time for Verlet integration is:") + print("[#]\nTime for Verlet integration is:") print("\(verletTime)") let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01); - print("[#] Time for Stormer Verlet integration is:") + print("[#]\nTime for Stormer Verlet integration is:") print("\(stormer.time)") - print("[#] Velocity for Stormer Verlet integration is:") + print("[#]\nVelocity for Stormer Verlet integration is:") print("\(stormer.vel)") let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01) - print("[#] Time for velocity Verlet integration is:") + print("[#]\nTime for velocity Verlet integration is:") print("\(velVerlet.time)") - print("[#] Velocity for velocity Verlet integration is:") + print("[#]\nVelocity for velocity Verlet integration is:") print("\(velVerlet.vel)") } From f3bd8f44ac6010b78e19dc2061b8bd3ba4ec10ca Mon Sep 17 00:00:00 2001 From: Mahdi <24981501+mahdisarikhani@users.noreply.github.com> Date: Mon, 11 Oct 2021 18:03:55 +0330 Subject: [PATCH 45/90] Add approximate counting algorithm in C (#844) * Add approximate counting algorithm in C * Fix typo Co-authored-by: stormofice <58337328+stormofice@users.noreply.github.com> Co-authored-by: stormofice <58337328+stormofice@users.noreply.github.com> Co-authored-by: James Schloss --- .../approximate_counting.md | 2 + .../code/c/approximate_counting.c | 82 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 contents/approximate_counting/code/c/approximate_counting.c diff --git a/contents/approximate_counting/approximate_counting.md b/contents/approximate_counting/approximate_counting.md index f63d7db43..654721844 100644 --- a/contents/approximate_counting/approximate_counting.md +++ b/contents/approximate_counting/approximate_counting.md @@ -360,6 +360,8 @@ As we do not have any objects to count, we will instead simulate the counting wi {% method %} {% sample lang="jl" %} [import, lang:"julia"](code/julia/approximate_counting.jl) +{% sample lang="c" %} +[import, lang:"c"](code/c/approximate_counting.c) {% sample lang="cpp" %} [import, lang:"cpp"](code/c++/approximate_counting.cpp) {% sample lang="python" %} diff --git a/contents/approximate_counting/code/c/approximate_counting.c b/contents/approximate_counting/code/c/approximate_counting.c new file mode 100644 index 000000000..ded7a518e --- /dev/null +++ b/contents/approximate_counting/code/c/approximate_counting.c @@ -0,0 +1,82 @@ +#include +#include +#include +#include +#include + +// This function returns a pseudo-random number between 0 and 1 +double drand() +{ + return (double)rand() / RAND_MAX; +} + +// This function takes +// - v: value in register +// - a: a scaling value for the logarithm based on Morris's paper +// It returns the approximate count +double n(double v, double a) +{ + return a * (pow(1 + 1 / a, v) - 1); +} + +// This function takes +// - v: value in register +// - a: a scaling value for the logarithm based on Morris's paper +// It returns a new value for v +double increment(double v, double a) +{ + // delta is the probability of incrementing our counter + double delta = 1 / (n(v + 1, a) - n(v, a)); + + if (drand() <= delta) { + return v + 1; + } + return v; +} + +// This function simulates counting and takes +// - n_items: number of items to count and loop over +// - a: a scaling value for the logarithm based on Morris's paper +// It returns n(v, a), the approximate count +double approximate_count(size_t n_items, double a) +{ + int v = 0; + for (size_t i = 0; i < n_items; ++i) { + v = increment(v, a); + } + + return n(v, a); +} + +// This function takes +// - n_trials: the number of counting trials +// - n_items: the number off items to count +// - a: a scaling value for the logarithm based on Morris's paper +// - threshold: the maximum percent error allowed +// It terminates the program on failure +void test_approximation_count(size_t n_trials, size_t n_items, double a, + double threshold) +{ + double sum = 0.0; + for (size_t i = 0; i < n_trials; ++i) { + sum += approximate_count(n_items, a); + } + double avg = sum / n_trials; + + assert(fabs((avg - n_items) / n_items) < threshold); +} + +int main() +{ + srand(time(NULL)); + + printf("Counting Tests, 100 trials\n"); + printf("testing 1000, a = 30, 1%% error\n"); + test_approximation_count(100, 1000, 30, 0.1); + printf("testing 12345, a = 10, 1%% error\n"); + test_approximation_count(100, 12345, 10, 0.1); + printf("testing 222222, a = 0.5, 10%% error\n"); + test_approximation_count(100, 222222, 0.5, 0.2); + + return 0; +} From d81942cd9c8060421cdb721f3745bf187531721f Mon Sep 17 00:00:00 2001 From: Ayman Lafaz Date: Tue, 12 Oct 2021 12:12:10 +0100 Subject: [PATCH 46/90] added 1d convolution implementation in python (#874) * added 1d convolution implementation in python * fixed some mistakes in the code so it outputs correct results * making the code look better * spacing code properly for readability --- contents/convolutions/1d/1d.md | 14 +++++ .../1d/code/python/1d_convolution.py | 53 +++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 contents/convolutions/1d/code/python/1d_convolution.py diff --git a/contents/convolutions/1d/1d.md b/contents/convolutions/1d/1d.md index d5d77652b..e3f9a3770 100644 --- a/contents/convolutions/1d/1d.md +++ b/contents/convolutions/1d/1d.md @@ -56,6 +56,8 @@ With this in mind, we can almost directly transcribe the discrete equation into [import:27-46, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:63-84, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:18-27, lang:"python"](code/python/1d_convolution.py) {% endmethod %} The easiest way to reason about this code is to read it as you might read a textbook. @@ -189,6 +191,8 @@ Here it is again for clarity: [import:27-46, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:63-84, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:18-27, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Here, the main difference between the bounded and unbounded versions is that the output array size is smaller in the bounded case. @@ -199,6 +203,8 @@ For an unbounded convolution, the function would be called with a the output arr [import:58-59, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:96-97, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:37-38, lang:"python"](code/python/1d_convolution.py) {% endmethod %} On the other hand, the bounded call would set the output array size to simply be the length of the signal @@ -208,6 +214,8 @@ On the other hand, the bounded call would set the output array size to simply be [import:61-62, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:98-99, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:40-41, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Finally, as we mentioned before, it is possible to center bounded convolutions by changing the location where we calculate the each point along the filter. @@ -218,6 +226,8 @@ This can be done by modifying the following line: [import:35-35, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:71-71, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:22-22, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Here, `j` counts from `i-length(filter)` to `i`. @@ -252,6 +262,8 @@ In code, this typically amounts to using some form of modulus operation, as show [import:4-25, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import:38-61, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import:5-15, lang:"python"](code/python/1d_convolution.py) {% endmethod %} This is essentially the same as before, except for the modulus operations, which allow us to work on a periodic domain. @@ -269,6 +281,8 @@ For the code associated with this chapter, we have used the convolution to gener [import, lang:"julia"](code/julia/1d_convolution.jl) {% sample lang="cs" %} [import, lang:"csharp"](code/csharp/1DConvolution.cs) +{% sample lang="py" %} +[import, lang:"python"](code/python/1d_convolution.py) {% endmethod %} At a test case, we have chosen to use two sawtooth functions, which should produce the following images: diff --git a/contents/convolutions/1d/code/python/1d_convolution.py b/contents/convolutions/1d/code/python/1d_convolution.py new file mode 100644 index 000000000..e77e68d09 --- /dev/null +++ b/contents/convolutions/1d/code/python/1d_convolution.py @@ -0,0 +1,53 @@ +import numpy as np + +def mod1(x, y): return ((x % y) + y) % y + +def convolve_cyclic(signal, filter_array): + output_size = max(len(signal), len(filter_array)) + out = np.zeros(output_size) + s = 0 + + for i in range(output_size): + for j in range(output_size): + if(mod1(i - j, output_size) < len(filter_array)): + s += signal[mod1(j - 1, output_size)] * filter_array[mod1(i - j, output_size)] + out[i] = s + s = 0 + + return out + + +def convolve_linear(signal, filter_array, output_size): + out = np.zeros(output_size) + s = 0 + + for i in range(output_size): + for j in range(max(0, i - len(filter_array)), i + 1): + if j < len(signal) and (i - j) < len(filter_array): + s += signal[j] * filter_array[i - j] + out[i] = s + s = 0 + + return out + +# sawtooth functions for x and y +x = [float(i + 1)/200 for i in range(200)] +y = [float(i + 1)/200 for i in range(200)] + +# Normalization is not strictly necessary, but good practice +x /= np.linalg.norm(x) +y /= np.linalg.norm(y) + +# full convolution, output will be the size of x + y - 1 +full_linear_output = convolve_linear(x, y, len(x) + len(y) - 1) + +# simple boundaries +simple_linear_output = convolve_linear(x, y, len(x)) + +# cyclic convolution +cyclic_output = convolve_cyclic(x, y) + +# outputting convolutions to different files for plotting in external code +np.savetxt('full_linear.dat', full_linear_output) +np.savetxt('simple_linear.dat', simple_linear_output) +np.savetxt('cyclic.dat', cyclic_output) From bfc180dcf353b43ed34b4b0e3ba21d8d4eb927c8 Mon Sep 17 00:00:00 2001 From: Ayman Lafaz Date: Tue, 12 Oct 2021 15:20:56 +0100 Subject: [PATCH 47/90] fixing 1d convolution markdown file (#879) --- contents/convolutions/1d/1d.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contents/convolutions/1d/1d.md b/contents/convolutions/1d/1d.md index e3f9a3770..9a2e652d1 100644 --- a/contents/convolutions/1d/1d.md +++ b/contents/convolutions/1d/1d.md @@ -57,7 +57,7 @@ With this in mind, we can almost directly transcribe the discrete equation into {% sample lang="cs" %} [import:63-84, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:18-27, lang:"python"](code/python/1d_convolution.py) +[import:20-31, lang:"python"](code/python/1d_convolution.py) {% endmethod %} The easiest way to reason about this code is to read it as you might read a textbook. @@ -192,7 +192,7 @@ Here it is again for clarity: {% sample lang="cs" %} [import:63-84, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:18-27, lang:"python"](code/python/1d_convolution.py) +[import:20-31, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Here, the main difference between the bounded and unbounded versions is that the output array size is smaller in the bounded case. @@ -204,7 +204,7 @@ For an unbounded convolution, the function would be called with a the output arr {% sample lang="cs" %} [import:96-97, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:37-38, lang:"python"](code/python/1d_convolution.py) +[import:41-42, lang:"python"](code/python/1d_convolution.py) {% endmethod %} On the other hand, the bounded call would set the output array size to simply be the length of the signal @@ -215,7 +215,7 @@ On the other hand, the bounded call would set the output array size to simply be {% sample lang="cs" %} [import:98-99, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:40-41, lang:"python"](code/python/1d_convolution.py) +[import:44-45, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Finally, as we mentioned before, it is possible to center bounded convolutions by changing the location where we calculate the each point along the filter. @@ -227,7 +227,7 @@ This can be done by modifying the following line: {% sample lang="cs" %} [import:71-71, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:22-22, lang:"python"](code/python/1d_convolution.py) +[import:25-25, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Here, `j` counts from `i-length(filter)` to `i`. @@ -263,7 +263,7 @@ In code, this typically amounts to using some form of modulus operation, as show {% sample lang="cs" %} [import:38-61, lang:"csharp"](code/csharp/1DConvolution.cs) {% sample lang="py" %} -[import:5-15, lang:"python"](code/python/1d_convolution.py) +[import:5-17, lang:"python"](code/python/1d_convolution.py) {% endmethod %} This is essentially the same as before, except for the modulus operations, which allow us to work on a periodic domain. From 1c820498272a6d97b2418925ac939f5b66528f8b Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Fri, 15 Oct 2021 21:32:35 +0200 Subject: [PATCH 48/90] Add racket setup to devcontainer (#875) --- .devcontainer/Dockerfile | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index e014b404b..a7bda0bd3 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -73,7 +73,8 @@ RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D6 RUN sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/' # Setup Racket -## Use: https://ubunlog.com/en/racket-install-ubuntu-programming-language +RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D9D33FCD84D82C17288BA03B3C9A6980F827E01E +RUN sudo add-apt-repository 'deb http://ppa.launchpad.net/plt/racket/ubuntu focal main' # Setup Scheme ## Use: https://github.com/ashinn/chibi-scheme @@ -99,7 +100,7 @@ RUN sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu fo # Install the packages that needed extra help RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ - && apt-get -y install --no-install-recommends crystal dart nim powershell scala dotnet-sdk-5.0 r-base + && apt-get -y install --no-install-recommends crystal dart nim powershell scala dotnet-sdk-5.0 r-base racket RUN pip install wheel matplotlib numpy coconut From c206831d9c9b75c7019e27bb9bc5a95c66162c8a Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Sat, 16 Oct 2021 19:01:30 +0200 Subject: [PATCH 49/90] Normalize inputs for scheme euclid algorithm (#878) Change inputs to make it consistent with other examples. --- contents/euclidean_algorithm/code/scheme/euclidalg.ss | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contents/euclidean_algorithm/code/scheme/euclidalg.ss b/contents/euclidean_algorithm/code/scheme/euclidalg.ss index 3d891ba73..959ebdeca 100644 --- a/contents/euclidean_algorithm/code/scheme/euclidalg.ss +++ b/contents/euclidean_algorithm/code/scheme/euclidalg.ss @@ -12,4 +12,5 @@ (euclid-mod b (modulo a b)))) (display (euclid-mod (* 64 67) (* 64 81))) (newline) -(display (euclid-sub (* 64 12) (* 64 27))) (newline) +(display (euclid-sub (* 128 12) (* 128 77))) (newline) + From a86911467345d938497c527471deed5808a811ff Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Sat, 16 Oct 2021 19:14:44 +0200 Subject: [PATCH 50/90] Add initial setup for Swift in devcontainer (#880) --- .devcontainer/Dockerfile | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index a7bda0bd3..8cb8c2ab7 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -83,7 +83,9 @@ RUN sudo add-apt-repository 'deb http://ppa.launchpad.net/plt/racket/ubuntu foca ## using 1.x right now.... in future checkout snap or adobe air? # Setup Swift -## ? +RUN mkdir -p ~/swift && wget https://swift.org/builds/swift-5.5-release/ubuntu2004/swift-5.5-RELEASE/swift-5.5-RELEASE-ubuntu20.04.tar.gz -O ~/swift/swift.tar.gz && \ + tar -xzf ~/swift/swift.tar.gz -C ~/swift --strip-components=1 +ENV PATH=$PATH:~/swift/usr/bin # Setup viml ## ? From cee127059873340b68d7a653ed2f1943e3e9cc85 Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Sat, 16 Oct 2021 19:15:51 +0200 Subject: [PATCH 51/90] Add scheme setup to devcontainer (#876) --- .devcontainer/Dockerfile | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index 8cb8c2ab7..bc58ae358 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -72,13 +72,11 @@ ENV PATH=$PATH:/root/factor/factor RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 RUN sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu focal-cran40/' -# Setup Racket +# Setup Racket and Scheme +# To run scheme files, use `racket -f ` RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys D9D33FCD84D82C17288BA03B3C9A6980F827E01E RUN sudo add-apt-repository 'deb http://ppa.launchpad.net/plt/racket/ubuntu focal main' -# Setup Scheme -## Use: https://github.com/ashinn/chibi-scheme - # Setup Scratch ## using 1.x right now.... in future checkout snap or adobe air? From d631070d310132f996bc52caebadeec0a7990104 Mon Sep 17 00:00:00 2001 From: Eric Berquist Date: Mon, 18 Oct 2021 13:52:46 +0000 Subject: [PATCH 52/90] Clean up Monte Carlo integration in Racket (#781) * Clean up Monte Carlo integration in Racket * Add blank lines in Monte Carlo integration in Clojure * Change Racket lang include from lisp to racket --- .../code/clojure/monte_carlo.clj | 5 ++- .../code/racket/monte_carlo.rkt | 39 ++++++++++--------- .../monte_carlo_integration.md | 4 +- 3 files changed, 27 insertions(+), 21 deletions(-) diff --git a/contents/monte_carlo_integration/code/clojure/monte_carlo.clj b/contents/monte_carlo_integration/code/clojure/monte_carlo.clj index f66baef67..de517e56c 100644 --- a/contents/monte_carlo_integration/code/clojure/monte_carlo.clj +++ b/contents/monte_carlo_integration/code/clojure/monte_carlo.clj @@ -8,9 +8,11 @@ (map #(* % %)) (reduce +)) (* r r))) + (defn rand-point [r] "return a random point from (0,0) inclusive to (r,r) exclusive" (repeatedly 2 #(rand r))) + (defn monte-carlo [n r] "take the number of random points and radius return an estimate to pi" @@ -22,11 +24,12 @@ pi" (if (in-circle? (rand-point r) r) (inc count) count)))))) + (defn -main [] (let [constant-pi Math/PI computed-pi (monte-carlo 10000000 2) ;; this may take some time on lower end machines difference (Math/abs (- constant-pi computed-pi)) error (* 100 (/ difference constant-pi))] (println "world's PI: " constant-pi - ",our PI: " (double computed-pi) + ",our PI: " (double computed-pi) ",error: " error))) diff --git a/contents/monte_carlo_integration/code/racket/monte_carlo.rkt b/contents/monte_carlo_integration/code/racket/monte_carlo.rkt index 0f652db93..0278e7ed6 100755 --- a/contents/monte_carlo_integration/code/racket/monte_carlo.rkt +++ b/contents/monte_carlo_integration/code/racket/monte_carlo.rkt @@ -1,22 +1,25 @@ -#lang racket -(define (in_circle x y) - (< (+ (sqr x) (sqr y)) 1) - ) +#lang racket/base -(define (monte_carlo_pi n) - (* (/ (local ((define (monte_carlo* n count) +(require racket/local) +(require racket/math) + +(define (in-circle x y) + "Checks if a point is in a unit circle" + (< (+ (sqr x) (sqr y)) 1)) + +(define (monte-carlo-pi n) + "Returns an approximation of pi" + (* (/ (local ((define (monte-carlo-pi* n count) (if (= n 0) count - (monte_carlo_pi* (sub1 n) - (if (in_circle (random) (random)) - (add1 count) - count - ) - ) - ) - )) (monte_carlo_pi* n 0) - ) n) 4) - ) - + (monte-carlo-pi* (sub1 n) + (if (in-circle (random) (random)) + (add1 count) + count))))) + (monte-carlo-pi* n 0)) n) 4)) -(display (monte_carlo_pi 1000)) +(define nsamples 5000000) +(define pi-estimate (monte-carlo-pi nsamples)) +(displayln (string-append "Estimate (rational): " (number->string pi-estimate))) +(displayln (string-append "Estimate (float): " (number->string (real->single-flonum pi-estimate)))) +(displayln (string-append "Error:" (number->string (* (/ (abs (- pi-estimate pi)) pi) 100)))) diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index ac6895404..cf5640ffa 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -80,7 +80,7 @@ each point is tested to see whether it's in the circle or not: {% sample lang="lua" %} [import:2-4, lang="lua"](code/lua/monte_carlo.lua) {% sample lang="racket" %} -[import:2-4, lang:"lisp"](code/racket/monte_carlo.rkt) +[import:6-8, lang:"racket"](code/racket/monte_carlo.rkt) {% sample lang="scala" %} [import:3-3, lang:"scala"](code/scala/monte_carlo.scala) {% sample lang="lisp" %} @@ -188,7 +188,7 @@ Feel free to submit your version via pull request, and thanks for reading! {% sample lang="lua" %} [import, lang="lua"](code/lua/monte_carlo.lua) {% sample lang="racket" %} -[import, lang:"lisp"](code/racket/monte_carlo.rkt) +[import, lang:"racket"](code/racket/monte_carlo.rkt) {% sample lang="scala" %} [import, lang:"scala"](code/scala/monte_carlo.scala) {% sample lang="lisp" %} From 7f814fa755734a92bbe299f56e69be4ba4148056 Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Mon, 18 Oct 2021 17:44:55 +0200 Subject: [PATCH 53/90] Add C++ code for Flood Fill algorithm (#860) --- CONTRIBUTORS.md | 1 + contents/flood_fill/code/cpp/flood_fill.cpp | 156 ++++++++++++++++++++ contents/flood_fill/flood_fill.md | 10 ++ 3 files changed, 167 insertions(+) create mode 100644 contents/flood_fill/code/cpp/flood_fill.cpp diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fb8ecde19..e3707e290 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -59,3 +59,4 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Mahdi Sarikhani - Ridham177 - Hugo Salou +- Dimitri Belopopsky diff --git a/contents/flood_fill/code/cpp/flood_fill.cpp b/contents/flood_fill/code/cpp/flood_fill.cpp new file mode 100644 index 000000000..918566809 --- /dev/null +++ b/contents/flood_fill/code/cpp/flood_fill.cpp @@ -0,0 +1,156 @@ +#include +#include +#include +#include +#include +#include + +using CartesianIndex = std::array; + +auto inbounds(CartesianIndex size, CartesianIndex loc) { + if (loc[0] < 0 || loc[1] < 0) { + return false; + } else if (loc[0] >= size[0] || loc[1] >= size[1]) { + return false; + } + return true; +} + +auto find_neighbors( + std::vector> const& grid, + CartesianIndex loc, + float old_value, + float /* new_value */) { + + const std::vector possible_neighbors{ + {loc[0], loc[1] + 1}, + {loc[0] + 1, loc[1]}, + {loc[0], loc[1] - 1}, + {loc[0] - 1, loc[1]}}; + + std::vector neighbors; + + for (auto const& possible_neighbor : possible_neighbors) { + const auto size = CartesianIndex{ + static_cast(grid[0].size()), static_cast(grid.size())}; + const auto x = static_cast(possible_neighbor[0]); + const auto y = static_cast(possible_neighbor[1]); + if (inbounds(size, possible_neighbor) && grid[x][y] == old_value) { + neighbors.push_back(possible_neighbor); + } + } + + return neighbors; +} + +void recursive_fill( + std::vector>& grid, + CartesianIndex loc, + float old_value, + float new_value) { + if (old_value == new_value) { + return; + } + + const auto x = static_cast(loc[0]); + const auto y = static_cast(loc[1]); + + grid[x][y] = new_value; + + const auto possible_neighbors = find_neighbors(grid, loc, old_value, new_value); + for (auto const& possible_neighbor : possible_neighbors) { + recursive_fill(grid, possible_neighbor, old_value, new_value); + } +} + +void queue_fill( + std::vector>& grid, + CartesianIndex loc, + float old_value, + float new_value) { + if (old_value == new_value) { + return; + } + + auto q = std::queue{}; + q.push(loc); + const auto x = static_cast(loc[0]); + const auto y = static_cast(loc[1]); + grid[x][y] = new_value; + + while (q.size() > 0) { + const auto current_loc = q.front(); + q.pop(); + const auto possible_neighbors = + find_neighbors(grid, current_loc, old_value, new_value); + for (auto const& neighbor : possible_neighbors) { + const auto neighbor_x = static_cast(neighbor[0]); + const auto neighbor_y = static_cast(neighbor[1]); + grid[neighbor_x][neighbor_y] = new_value; + q.push(neighbor); + } + } +} + +void stack_fill( + std::vector>& grid, + CartesianIndex loc, + float old_value, + float new_value) { + if (old_value == new_value) { + return; + } + + auto s = std::stack{}; + s.push(loc); + + while (s.size() > 0) { + const auto current_loc = s.top(); + s.pop(); + + const auto x = static_cast(current_loc[0]); + const auto y = static_cast(current_loc[1]); + + if (grid[x][y] == old_value) { + grid[x][y] = new_value; + const auto possible_neighbors = + find_neighbors(grid, current_loc, old_value, new_value); + for (auto const& neighbor : possible_neighbors) { + s.push(neighbor); + } + } + } +} + +int main() { + + const std::vector> grid{ + {0, 0, 1, 0, 0}, + {0, 0, 1, 0, 0}, + {0, 0, 1, 0, 0}, + {0, 0, 1, 0, 0}, + {0, 0, 1, 0, 0}}; + + const std::vector> solution_grid{ + {1, 1, 1, 0, 0}, + {1, 1, 1, 0, 0}, + {1, 1, 1, 0, 0}, + {1, 1, 1, 0, 0}, + {1, 1, 1, 0, 0}}; + + const CartesianIndex start_loc{1, 1}; + + auto test_grid = grid; + recursive_fill(test_grid, start_loc, 0.0, 1.0); + assert(test_grid == solution_grid); + + test_grid = grid; + queue_fill(test_grid, start_loc, 0.0, 1.0); + assert(test_grid == solution_grid); + + test_grid = grid; + stack_fill(test_grid, start_loc, 0.0, 1.0); + assert(test_grid == solution_grid); + + return EXIT_SUCCESS; +} \ No newline at end of file diff --git a/contents/flood_fill/flood_fill.md b/contents/flood_fill/flood_fill.md index 185050fe1..4c7e5936e 100644 --- a/contents/flood_fill/flood_fill.md +++ b/contents/flood_fill/flood_fill.md @@ -90,6 +90,8 @@ In code, this might look like this: [import:23-41, lang:"julia"](code/julia/flood_fill.jl) {% sample lang="c" %} [import:28-46, lang:"c"](code/c/flood_fill.c) +{% sample lang="cpp" %} +[import:19-44, lang:"cpp"](code/cpp/flood_fill.cpp) {% sample lang="py" %} [import:10-25, lang="python"](code/python/flood_fill.py) {% sample lang="coco" %} @@ -110,6 +112,8 @@ In code, it might look like this: [import:92-104, lang:"julia"](code/julia/flood_fill.jl) {% sample lang="c" %} [import:174-189, lang:"c"](code/c/flood_fill.c) +{% sample lang="cpp" %} +[import:46-64, lang:"cpp"](code/cpp/flood_fill.cpp) {% sample lang="py" %} [import:55-63, lang="python"](code/python/flood_fill.py) {% sample lang="coco" %} @@ -125,6 +129,8 @@ Additionally, it is possible to do the same type of traversal by managing a stac [import:43-63, lang:"julia"](code/julia/flood_fill.jl) {% sample lang="c" %} [import:79-102, lang:"c"](code/c/flood_fill.c) +{% sample lang="cpp" %} +[import:95-123, lang:"cpp"](code/cpp/flood_fill.cpp) {% sample lang="py" %} [import:27-36, lang="python"](code/python/flood_fill.py) {% sample lang="coco" %} @@ -168,6 +174,8 @@ The code would look something like this: [import:66-90, lang:"julia"](code/julia/flood_fill.jl) {% sample lang="c" %} [import:149-172, lang:"c"](code/c/flood_fill.c) +{% sample lang="cpp" %} +[import:66-93, lang:"cpp"](code/cpp/flood_fill.cpp) {% sample lang="py" %} [import:38-53, lang="python"](code/python/flood_fill.py) {% sample lang="coco" %} @@ -250,6 +258,8 @@ After, we will fill in the left-hand side of the array to be all ones by choosin [import, lang:"julia"](code/julia/flood_fill.jl) {% sample lang="c" %} [import, lang:"c"](code/c/flood_fill.c) +{% sample lang="cpp" %} +[import, lang:"cpp"](code/cpp/flood_fill.cpp) {% sample lang="py" %} [import:, lang="python"](code/python/flood_fill.py) {% sample lang="coco" %} From 65599eed94658d039105c5c66ca386c11a3df8ff Mon Sep 17 00:00:00 2001 From: James Schloss Date: Wed, 20 Oct 2021 13:41:31 +0200 Subject: [PATCH 54/90] fixing chapter to use split-op code (#888) --- contents/quantum_systems/code/c++/energy.cpp | 59 ------------------ contents/quantum_systems/code/c/energy.c | 61 ------------------- .../quantum_systems/code/haskell/Energy.hs | 14 ----- contents/quantum_systems/code/julia/energy.jl | 18 ------ .../quantum_systems/code/python/energy.py | 17 ------ contents/quantum_systems/quantum_systems.md | 10 +-- 6 files changed, 5 insertions(+), 174 deletions(-) delete mode 100644 contents/quantum_systems/code/c++/energy.cpp delete mode 100644 contents/quantum_systems/code/c/energy.c delete mode 100644 contents/quantum_systems/code/haskell/Energy.hs delete mode 100644 contents/quantum_systems/code/julia/energy.jl delete mode 100644 contents/quantum_systems/code/python/energy.py diff --git a/contents/quantum_systems/code/c++/energy.cpp b/contents/quantum_systems/code/c++/energy.cpp deleted file mode 100644 index 15a58bd01..000000000 --- a/contents/quantum_systems/code/c++/energy.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include -#include - -#include - -void fft(std::vector> &x, bool inverse) { - std::vector> y(x.size(), std::complex(0.0, 0.0)); - - fftw_plan p; - - fftw_complex *in = reinterpret_cast(x.data()); - fftw_complex *out = reinterpret_cast(y.data()); - - p = fftw_plan_dft_1d(x.size(), in, out, - (inverse ? FFTW_BACKWARD : FFTW_FORWARD), FFTW_ESTIMATE); - - - fftw_execute(p); - fftw_destroy_plan(p); - - for (size_t i = 0; i < x.size(); ++i) { - x[i] = y[i] / sqrt(static_cast(x.size())); - } -} - -double calculate_energy(std::vector> wfc, - std::vector> h_r, - std::vector> h_k, - double dx, size_t size) { - std::vector> wfc_k(wfc); - std::vector> wfc_c(size); - fft(wfc_k, false); - - for (size_t i = 0; i < size; ++i) { - wfc_c[i] = conj(wfc[i]); - } - - std::vector> energy_k(size); - std::vector> energy_r(size); - - for (size_t i = 0; i < size; ++i) { - energy_k[i] = wfc_k[i] * pow(h_k[i], 2); - } - - fft(energy_k, true); - - for (size_t i = 0; i < size; ++i) { - energy_k[i] *= 0.5 * wfc_c[i]; - energy_r[i] = wfc_c[i] * h_r[i] * wfc[i]; - } - - double energy_final = 0; - - for (size_t i = 0; i < size; ++i) { - energy_final += real(energy_k[i] + energy_r[i]); - } - - return energy_final * dx; -} diff --git a/contents/quantum_systems/code/c/energy.c b/contents/quantum_systems/code/c/energy.c deleted file mode 100644 index 9086ffcd5..000000000 --- a/contents/quantum_systems/code/c/energy.c +++ /dev/null @@ -1,61 +0,0 @@ -#include -#include -#include -#include - -#include - -void fft(double complex *x, int n, bool inverse) { - double complex y[n]; - memset(y, 0, sizeof(y)); - fftw_plan p; - - if (inverse) { - p = fftw_plan_dft_1d(n, (fftw_complex*)x, (fftw_complex*)y, - FFTW_BACKWARD, FFTW_ESTIMATE); - } else { - p = fftw_plan_dft_1d(n, (fftw_complex*)x, (fftw_complex*)y, - FFTW_FORWARD, FFTW_ESTIMATE); - } - - fftw_execute(p); - fftw_destroy_plan(p); - - for (size_t i = 0; i < n; ++i) { - x[i] = y[i] / sqrt((double)n); - } -} - -double calculate_energy(double complex *wfc, double complex *h_r, - double complex *h_k, double dx, size_t size) { - double complex wfc_k[size]; - double complex wfc_c[size]; - memcpy(wfc_k, wfc, sizeof(wfc_k)); - fft(wfc_k, size, false); - - for (size_t i = 0; i < size; ++i) { - wfc_c[i] = conj(wfc[i]); - } - - double complex energy_k[size]; - double complex energy_r[size]; - - for (size_t i = 0; i < size; ++i) { - energy_k[i] = wfc_k[i] * h_k[i]; - } - - fft(energy_k, size, true); - - for (size_t i = 0; i < size; ++i) { - energy_k[i] *= wfc_c[i]; - energy_r[i] = wfc_c[i] * h_r[i] * wfc[i]; - } - - double energy_final = 0; - - for (size_t i = 0; i < size; ++i) { - energy_final += creal(energy_k[i] + energy_r[i]); - } - - return energy_final * dx; -} diff --git a/contents/quantum_systems/code/haskell/Energy.hs b/contents/quantum_systems/code/haskell/Energy.hs deleted file mode 100644 index a024fd139..000000000 --- a/contents/quantum_systems/code/haskell/Energy.hs +++ /dev/null @@ -1,14 +0,0 @@ -import Data.Array.CArray -import Data.Complex -import Math.FFT (dft, idft) -- Binding to fftw - -type Vector = CArray Int (Complex Double) - -calculateEnergy :: Double -> Vector -> Vector -> Vector -> Double -calculateEnergy dx kin pot wfc = (* dx) . sum . map realPart $ elems total - where - total = liftArray2 (+) kineticE potentialE - potentialE = wfcConj .* pot .* wfc - kineticE = wfcConj .* idft (kin .* dft wfc) - wfcConj = liftArray conjugate wfc - a .* b = liftArray2 (*) a b diff --git a/contents/quantum_systems/code/julia/energy.jl b/contents/quantum_systems/code/julia/energy.jl deleted file mode 100644 index 3efce0cb7..000000000 --- a/contents/quantum_systems/code/julia/energy.jl +++ /dev/null @@ -1,18 +0,0 @@ -# We are calculating the energy to check -function calculate_energy(wfc, H_k, H_r, dx) - # Creating momentum and conjugate wavefunctions - wfc_k = fft(wfc) - wfc_c = conj(wfc) - - # Finding the momentum and real-space energy terms - energy_k = wfc_c.*ifft((H_k) .* wfc_k) - energy_r = wfc_c.* H_r .* wfc - - # Integrating over all space - energy_final = 0 - for i = 1:length(energy_k) - energy_final += real(energy_k[i] + energy_r[i]) - end - - return energy_final*dx -end diff --git a/contents/quantum_systems/code/python/energy.py b/contents/quantum_systems/code/python/energy.py deleted file mode 100644 index 328fa9950..000000000 --- a/contents/quantum_systems/code/python/energy.py +++ /dev/null @@ -1,17 +0,0 @@ -import numpy as np - - -def calculate_energy(wfc, H_k, H_r, dx): - """Calculate the energy .""" - # Creating momentum conjugate wavefunctions - wfc_k = np.fft.fft(wfc) - wfc_c = np.conj(wfc) - - # Finding the momentum and real-space energy terms - energy_k = 0.5 * wfc_c * np.fft.ifft((H_k ** 2) * wfc_k) - energy_r = wfc_c * H_r * wfc - - # Integrating over all space - energy_final = sum(energy_k + energy_r).real - - return energy_final * dx diff --git a/contents/quantum_systems/quantum_systems.md b/contents/quantum_systems/quantum_systems.md index a74c22068..a7a762ca5 100644 --- a/contents/quantum_systems/quantum_systems.md +++ b/contents/quantum_systems/quantum_systems.md @@ -226,15 +226,15 @@ This ultimately looks like this: {% method %} {% sample lang="jl" %} -[import, lang:"julia"](code/julia/energy.jl) +[import:114-132, lang:"julia"](../split-operator_method/code/julia/split_op.jl) {% sample lang="hs" %} -[import, lang:"haskell"](code/haskell/Energy.hs) +[import:75-82, lang:"haskell"](../split-operator_method/code/haskell/splitOp.hs) {% sample lang="c" %} -[import:29-, lang:"c"](code/c/energy.c) +[import:150-184, lang:"c"](../split-operator_method/code/c/split_op.c) {% sample lang="cpp" %} -[import:26-, lang:"cpp"](code/c++/energy.cpp) +[import:158-189, lang:"cpp"](../split-operator_method/code/c++/split_op.cpp) {% sample lang="py" %} -[import:4-17, lang:"python"](code/python/energy.py) +[import:98-112, lang:"python"](../split-operator_method/code/python/split_op.py) {% endmethod %} This calculation will be used in many different simulations of quantum systems to check our results. From c7c05a520544b7f9759602affafa4ca2b8e80adf Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 21 Oct 2021 11:39:24 +0530 Subject: [PATCH 55/90] use [#]\n for readability --- contents/tree_traversal/code/c++/tree_example.cpp | 10 +++++----- contents/tree_traversal/code/c/tree_traversal.c | 10 +++++----- contents/tree_traversal/code/clisp/tree-traversal.lisp | 10 +++++----- .../tree_traversal/code/coconut/tree_traversal.coco | 10 +++++----- contents/tree_traversal/code/crystal/tree-traversal.cr | 10 +++++----- contents/tree_traversal/code/csharp/Program.cs | 10 +++++----- contents/tree_traversal/code/golang/treetraversal.go | 10 +++++----- contents/tree_traversal/code/haskell/TreeTraversal.hs | 10 +++++----- contents/tree_traversal/code/java/MainClass.java | 10 +++++----- contents/tree_traversal/code/javascript/tree.js | 10 +++++----- contents/tree_traversal/code/julia/Tree.jl | 10 +++++----- contents/tree_traversal/code/php/tree_traversal.php | 10 +++++----- contents/tree_traversal/code/python/tree_traversal.py | 10 +++++----- contents/tree_traversal/code/rust/tree.rs | 10 +++++----- contents/tree_traversal/code/swift/tree.swift | 10 +++++----- 15 files changed, 75 insertions(+), 75 deletions(-) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index d109f11e5..71a84c686 100644 --- a/contents/tree_traversal/code/c++/tree_example.cpp +++ b/contents/tree_traversal/code/c++/tree_example.cpp @@ -102,19 +102,19 @@ int main() { // Creating Tree in main auto root = create_tree(2, 3); auto binary_root = create_tree(3, 2); - std::cout << "[#] Recursive DFS:\n"; + std::cout << "[#]\nRecursive DFS:\n"; dfs_recursive(root); std::cout << '\n'; - std::cout << "[#] Recursive Postorder DFS:\n"; + std::cout << "[#]\nRecursive Postorder DFS:\n"; dfs_recursive_postorder(root); std::cout << '\n'; - std::cout << "[#] Stack-based DFS:\n"; + std::cout << "[#]\nStack-based DFS:\n"; dfs_stack(root); std::cout << '\n'; - std::cout << "[#] Queue-based BFS:\n"; + std::cout << "[#]\nQueue-based BFS:\n"; bfs_queue(root); std::cout << '\n'; - std::cout << "[#] Recursive Inorder DFS for Binary Tree:\n"; + std::cout << "[#]\nRecursive Inorder DFS for Binary Tree:\n"; dfs_recursive_inorder_btree(binary_root); std::cout << '\n'; diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index bc01ed609..16be536c8 100644 --- a/contents/tree_traversal/code/c/tree_traversal.c +++ b/contents/tree_traversal/code/c/tree_traversal.c @@ -115,26 +115,26 @@ void bfs_queue(struct node n) { int main() { struct node root = create_tree(2, 3); - printf("[#] Recursive DFS:\n"); + printf("[#]\nRecursive DFS:\n"); dfs_recursive(root); printf("\n"); - printf("[#] Recursive Postorder DFS:\n"); + printf("[#]\nRecursive Postorder DFS:\n"); dfs_recursive_postorder(root); printf("\n"); - printf("[#] Stack-based DFS:\n"); + printf("[#]\nStack-based DFS:\n"); dfs_stack(root); printf("\n"); - printf("[#] Queue-based BFS:\n"); + printf("[#]\nQueue-based BFS:\n"); bfs_queue(root); printf("\n"); destroy_tree(root); struct node root_binary = create_tree(3, 2); - printf("[#] Recursive Inorder DFS for Binary Tree:\n"); + printf("[#]\nRecursive Inorder DFS for Binary Tree:\n"); dfs_recursive_inorder_btree(root_binary); printf("\n"); diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 31395f3ac..8c74db43b 100644 --- a/contents/tree_traversal/code/clisp/tree-traversal.lisp +++ b/contents/tree_traversal/code/clisp/tree-traversal.lisp @@ -73,26 +73,26 @@ (defvar binary-tree (make-tree 3 2)) ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 -(format t "[#] Recursive DFS:~%") +(format t "[#]~%Recursive DFS:~%") (dfs-recursive tree) (format t "~%") ;; Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 -(format t "[#] Recursive Postorder DFS:~%") +(format t "[#]~%Recursive Postorder DFS:~%") (dfs-recursive-postorder tree) (format t "~%") ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 -(format t "[#] Stack-based DFS:~%") +(format t "[#]~%Stack-based DFS:~%") (dfs-stack tree) (format t "~%") ;; Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 -(format t "[#] Queue-based BFS:~%") +(format t "[#]~%Queue-based BFS:~%") (bfs-queue tree) (format t "~%") ;; Should print: 1 2 1 3 1 2 1 -(format t "[#] Recursive Inorder DFS for Binary Tree:~%") +(format t "[#]~%Recursive Inorder DFS for Binary Tree:~%") (dfs-recursive-inorder-btree binary-tree) (format t "~%") diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index 228d4aab7..776708f6e 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -61,26 +61,26 @@ if __name__ =='__main__': # A ternary tree for testing tree = create_tree(2, 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfs_recursive(tree) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfs_recursive_postorder(tree) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfs_stack(tree) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfs_queue(tree) print() # And a binary tree for testing binary_tree = create_tree(3, 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() diff --git a/contents/tree_traversal/code/crystal/tree-traversal.cr b/contents/tree_traversal/code/crystal/tree-traversal.cr index dcd92773b..e63dbbb7e 100644 --- a/contents/tree_traversal/code/crystal/tree-traversal.cr +++ b/contents/tree_traversal/code/crystal/tree-traversal.cr @@ -63,25 +63,25 @@ end def main root = create_tree levels: 2, num_childs: 3 - puts "[#] Recursive DFS:" + puts "[#]\nRecursive DFS:" dfs_recursive root puts - puts "[#] Recursive Postorder DFS:" + puts "[#]\nRecursive Postorder DFS:" dfs_recursive_postorder root puts - puts "[#] Stack-based DFS:" + puts "[#]\nStack-based DFS:" dfs_stack root puts - puts "[#] Queue-based BFS:" + puts "[#]\nQueue-based BFS:" bfs_queue root puts root_bin = create_tree levels: 3, num_childs: 2 - puts "[#] Recursive Inorder DFS for Binary Tree:" + puts "[#]\nRecursive Inorder DFS for Binary Tree:" dfs_recursive_inorder_btree root_bin puts end diff --git a/contents/tree_traversal/code/csharp/Program.cs b/contents/tree_traversal/code/csharp/Program.cs index 646375c51..4308794dd 100644 --- a/contents/tree_traversal/code/csharp/Program.cs +++ b/contents/tree_traversal/code/csharp/Program.cs @@ -8,24 +8,24 @@ class Program static void Main(string[] args) { var tree = new Tree(2, 3); - Console.WriteLine("[#] Recursive DFS:"); + Console.WriteLine("[#]\nRecursive DFS:"); tree.DFSRecursive(); Console.WriteLine(); - Console.WriteLine("[#] Recursive Postorder DFS:"); + Console.WriteLine("[#]\nRecursive Postorder DFS:"); tree.DFSRecursivePostorder(); Console.WriteLine(); - Console.WriteLine("[#] Stack-based DFS:"); + Console.WriteLine("[#]\nStack-based DFS:"); tree.DFSStack(); Console.WriteLine(); - Console.WriteLine("[#] Queue-based BFS:"); + Console.WriteLine("[#]\nQueue-based BFS:"); tree.BFSQueue(); Console.WriteLine(); tree = new Tree(3, 2); - Console.WriteLine("[#] Recursive Inorder DFS for Binary Tree:"); + Console.WriteLine("[#]\nRecursive Inorder DFS for Binary Tree:"); tree.DFSRecursiveInorderBinary(); Console.WriteLine(); } diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index ac18ce262..fb5142712 100644 --- a/contents/tree_traversal/code/golang/treetraversal.go +++ b/contents/tree_traversal/code/golang/treetraversal.go @@ -77,23 +77,23 @@ func main() { root := createTree(2, 3) binTree := createTree(3, 2) - fmt.Println("[#] Recursive DFS:") + fmt.Println("[#]\nRecursive DFS:") dfsRecursive(root) fmt.Println() - fmt.Println("[#] Recursive Postorder DFS:") + fmt.Println("[#]\nRecursive Postorder DFS:") dfsRecursivePostorder(root) fmt.Println() - fmt.Println("[#] Stack-based DFS:") + fmt.Println("[#]\nStack-based DFS:") dfsStack(root) fmt.Println() - fmt.Println("[#] Queue-based BFS:") + fmt.Println("[#]\nQueue-based BFS:") bfsQueue(root) fmt.Println() - fmt.Println("[#] Recursive Inorder DFS for Binary Tree:") + fmt.Println("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInorderBtree(binTree) fmt.Println() diff --git a/contents/tree_traversal/code/haskell/TreeTraversal.hs b/contents/tree_traversal/code/haskell/TreeTraversal.hs index e851f1833..1f9d27db8 100644 --- a/contents/tree_traversal/code/haskell/TreeTraversal.hs +++ b/contents/tree_traversal/code/haskell/TreeTraversal.hs @@ -37,13 +37,13 @@ createTree numRow numChild = Node numRow children main = do let testTree = createTree 2 3 showNodes = unwords . map show - putStrLn "[#] Recursive DFS:" + putStrLn "[#]\nRecursive DFS:" putStrLn $ showNodes $ dfs testTree - putStrLn "[#] Recursive Postorder DFS:" + putStrLn "[#]\nRecursive Postorder DFS:" putStrLn $ showNodes $ dfsPostOrder testTree - putStrLn "[#] Stack-based DFS:" + putStrLn "[#]\nStack-based DFS:" putStrLn $ showNodes $ dfsStack testTree - putStrLn "[#] Queue-based BFS:" + putStrLn "[#]\nQueue-based BFS:" putStrLn $ showNodes $ bfs testTree - putStrLn "[#] Recursive Inorder DFS for Binary Tree:" + putStrLn "[#]\nRecursive Inorder DFS for Binary Tree:" putStrLn $ showNodes $ dfsInOrder $ createTree 3 2 diff --git a/contents/tree_traversal/code/java/MainClass.java b/contents/tree_traversal/code/java/MainClass.java index 470c58e89..d7c062c03 100644 --- a/contents/tree_traversal/code/java/MainClass.java +++ b/contents/tree_traversal/code/java/MainClass.java @@ -3,21 +3,21 @@ public class MainClass { public static void main(String[] args) { Tree tree = new Tree(2, 3); - System.out.println("[#] Recursive DFS:"); + System.out.println("[#]\nRecursive DFS:"); tree.dfsRecursive(); System.out.println(); - System.out.println("[#] Recursive Postorder DFS:"); + System.out.println("[#]\nRecursive Postorder DFS:"); tree.dfsRecursivePostOrder(); System.out.println(); - System.out.println("[#] Stack-based DFS:"); + System.out.println("[#]\nStack-based DFS:"); tree.dfsStack(); System.out.println(); - System.out.println("[#] Queue-based BFS:"); + System.out.println("[#]\nQueue-based BFS:"); tree.bfsQueue(); System.out.println(); @@ -27,7 +27,7 @@ public static void main(String[] args) { //tree.dfsRecursiveInOrderBinary(); tree = new Tree(3, 2); - System.out.println("[#] Recursive Inorder DFS for Binary Tree:"); + System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:"); tree.dfsRecursiveInOrderBinary(); System.out.println(); } diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index 24392a259..01985949a 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -52,20 +52,20 @@ function bfs(tree) { } const root = createTree(2, 3); -console.log("[#] Recursive DFS:"); +console.log("[#]\nRecursive DFS:"); dfsPreorder(root); console.log(); -console.log("[#] Recursive Postorder DFS:"); +console.log("[#]\nRecursive Postorder DFS:"); dfsPostorder(root); console.log(); -console.log("[#] Stack-based DFS:"); +console.log("[#]\nStack-based DFS:"); dfsIterative(root); console.log(); -console.log("[#] Queue-based BFS:"); +console.log("[#]\nQueue-based BFS:"); bfs(root); console.log(); const root_binary = createTree(3, 2); -console.log("[#] Recursive Inorder DFS for Binary Tree:"); +console.log("[#]\nRecursive Inorder DFS for Binary Tree:"); dfsInorder(root_binary); console.log(); diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index 652048c71..abc207074 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -86,24 +86,24 @@ end function main() root = create_tree(2, 3) - println("[#] Recursive DFS:") + println("[#]\nRecursive DFS:") DFS_recursive(root); println() - println("[#] Recursive Postorder DFS:") + println("[#]\nRecursive Postorder DFS:") DFS_recursive_postorder(root); println() - println("[#] Stack-based DFS:") + println("[#]\nStack-based DFS:") DFS_stack(root); println() - println("[#] Queue-based BFS:") + println("[#]\nQueue-based BFS:") BFS_queue(root); println() root_binary = create_tree(3,2) - println("[#] Recursive Inorder DFS for Binary Tree:") + println("[#]\nRecursive Inorder DFS for Binary Tree:") DFS_recursive_inorder_btree(root_binary) println() end diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index 0951cea79..3c829977b 100644 --- a/contents/tree_traversal/code/php/tree_traversal.php +++ b/contents/tree_traversal/code/php/tree_traversal.php @@ -118,19 +118,19 @@ function generate_tree(int $numOfRows, int $numOfChildren): Tree $node = generate_tree(2, 3); -echo '[#] Recursive DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive DFS:' . PHP_EOL; TreeTraversal::DFSRecursive($node); echo PHP_EOL; -echo '[#] Recursive Postorder DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive Postorder DFS:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); echo PHP_EOL; -echo '[#] Stack-based DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Stack-based DFS:' . PHP_EOL; TreeTraversal::DFSStack($node); echo PHP_EOL; -echo '[#] Queue-based BFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Queue-based BFS:' . PHP_EOL; TreeTraversal::DFSQueue($node); echo PHP_EOL; @@ -138,6 +138,6 @@ function generate_tree(int $numOfRows, int $numOfChildren): Tree // comment out the generation of the new tree below. // If you do that, an exception will be thrown $node = generate_tree(3, 2); -echo '[#] Recursive Inorder DFS for Binary Tree:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive Inorder DFS for Binary Tree:' . PHP_EOL; TreeTraversal::DFSRecursiveInorderBinary($node); echo PHP_EOL; diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py index 341f949f1..735837bdd 100644 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -76,25 +76,25 @@ def bfs_queue(node): def main(): tree = create_tree(Node(), 2, 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfs_recursive(tree) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfs_recursive_postorder(tree) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfs_stack(tree) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfs_queue(tree) print() binary_tree = create_tree(Node(), 3, 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index 35319454a..60e833858 100644 --- a/contents/tree_traversal/code/rust/tree.rs +++ b/contents/tree_traversal/code/rust/tree.rs @@ -78,23 +78,23 @@ fn create_tree(num_row: u64, num_child: u64) -> Node { fn main() { let root = create_tree(2, 3); - println!("[#] Recursive DFS:"); + println!("[#]\nRecursive DFS:"); dfs_recursive(&root); println!(); - println!("[#] Recursive Postorder DFS:"); + println!("[#]\nRecursive Postorder DFS:"); dfs_recursive_postorder(&root); println!(); - println!("[#] Stack-based DFS:"); + println!("[#]\nStack-based DFS:"); dfs_stack(&root); println!(); - println!("[#] Queue-based BFS:"); + println!("[#]\nQueue-based BFS:"); bfs_queue(&root); println!(); - println!("[#] Recursive Inorder DFS for Binary Tree:"); + println!("[#]\nRecursive Inorder DFS for Binary Tree:"); let root_binary = create_tree(3, 2); dfs_recursive_inorder_btree(&root_binary); println!(); diff --git a/contents/tree_traversal/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index 86e561435..ae64315ec 100644 --- a/contents/tree_traversal/code/swift/tree.swift +++ b/contents/tree_traversal/code/swift/tree.swift @@ -83,25 +83,25 @@ func bfsQueue(node: Node) { func main() { let root = createTree(numRows: 2, numChildren: 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfsRecursive(node: root) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfsRecursivePostOrder(node: root) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfsStack(node: root) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfsQueue(node: root) print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) print() } From 9eb11d52d1557a8eebb0cbc09b1da014e5f46bec Mon Sep 17 00:00:00 2001 From: PaddyKe <34421580+PaddyKe@users.noreply.github.com> Date: Sat, 23 Oct 2021 14:33:48 +0200 Subject: [PATCH 56/90] Implemented stacks and queues in Java (#897) --- .../stacks_and_queues/code/java/Queue.java | 71 ++++++++++++++++++ .../stacks_and_queues/code/java/Stack.java | 72 +++++++++++++++++++ .../stacks_and_queues/stacks_and_queues.md | 4 ++ 3 files changed, 147 insertions(+) create mode 100644 contents/stacks_and_queues/code/java/Queue.java create mode 100644 contents/stacks_and_queues/code/java/Stack.java diff --git a/contents/stacks_and_queues/code/java/Queue.java b/contents/stacks_and_queues/code/java/Queue.java new file mode 100644 index 000000000..bb349ec6d --- /dev/null +++ b/contents/stacks_and_queues/code/java/Queue.java @@ -0,0 +1,71 @@ +import java.util.List; +import java.util.ArrayList; + +public class QueueTest { + + public static void main(String[] args) { + IQueue intQueue = new Queue<>(); + + intQueue.enqueue(4); + intQueue.enqueue(5); + intQueue.enqueue(9); + + System.out.println(intQueue.dequeue()); + System.out.println(intQueue.size()); + System.out.println(intQueue.front()); + } + +} + + +interface IQueue { + + /* + * 'dequeue' removes the first element from the queue and returns it + */ + T dequeue(); + + /* + * 'enqueue' adds an element at the end of the queue and returns the new size + */ + int enqueue(T element); + + + /* + * 'size' returns the size of the queue + */ + int size(); + + /* + * 'front' returns the first element of the queue without removing it + */ + T front(); +} + + +public class Queue implements IQueue { + + private List list; + + public Queue() { + this.list = new ArrayList<>(); + } + + public T dequeue() { + return this.list.remove(0); + } + + public int enqueue(T element) { + this.list.add(element); + return this.size(); + } + + public int size() { + return this.list.size(); + } + + public T front() { + return this.list.get(0); + } + +} diff --git a/contents/stacks_and_queues/code/java/Stack.java b/contents/stacks_and_queues/code/java/Stack.java new file mode 100644 index 000000000..2d65a0e59 --- /dev/null +++ b/contents/stacks_and_queues/code/java/Stack.java @@ -0,0 +1,72 @@ +import java.util.List; +import java.util.ArrayList; + + +public class StackTest { + + public static void main(String[] args) { + IStack intStack = new Stack<>(); + + intStack.push(4); + intStack.push(5); + intStack.push(9); + + System.out.println(intStack.pop()); + System.out.println(intStack.size()); + System.out.println(intStack.top()); + } + +} + + +interface IStack { + /* + * 'pop' removed the last element from the stack and returns it + */ + T pop(); + + /* + * 'push' adds an element to at the end of the stack and returns the new size + */ + int push(T element); + + /* + * 'size' returns the length of the stack + */ + int size(); + + /* + * 'top' returns the first element of the stack + */ + T top(); +} + + +public class Stack implements IStack { + + private List list; + + public Stack() { + this.list = new ArrayList<>(); + } + + public T pop() { + return this.list.remove(this.size() - 1); + } + + public int push(T element) { + this.list.add(element); + return this.size(); + } + + public int size() { + return this.list.size(); + } + + public T top() { + return this.list.get(this.size() - 1); + } + +} + + diff --git a/contents/stacks_and_queues/stacks_and_queues.md b/contents/stacks_and_queues/stacks_and_queues.md index 11c7088f7..89a77be9a 100644 --- a/contents/stacks_and_queues/stacks_and_queues.md +++ b/contents/stacks_and_queues/stacks_and_queues.md @@ -18,12 +18,16 @@ Here is a simple implementation of a stack: {% method %} {% sample lang="ts" %} [import, lang:"typescript"](code/typescript/stack.ts) +{% sample lang="java" %} +[import, lang:"java"](code/java/Stack.java) {% endmethod %} Here is a simple implementation of a queue: {% method %} {% sample lang="ts" %} [import, lang:"typescript"](code/typescript/queue.ts) +{% sample lang="java" %} +[import, lang:"java" ](code/java/Queue.java) {% endmethod %} From 84e9d5d310acaf0b820a25819387e39e0cfb2acb Mon Sep 17 00:00:00 2001 From: Henrik Christensen Date: Sat, 23 Oct 2021 15:02:27 +0200 Subject: [PATCH 57/90] Java tree traversal: updated dfsRecursiveInOrderBinary (#899) --- contents/tree_traversal/code/java/Tree.java | 28 +++++++++++---------- contents/tree_traversal/tree_traversal.md | 12 ++++----- 2 files changed, 21 insertions(+), 19 deletions(-) diff --git a/contents/tree_traversal/code/java/Tree.java b/contents/tree_traversal/code/java/Tree.java index 1dee7d9d1..b5c3d6542 100644 --- a/contents/tree_traversal/code/java/Tree.java +++ b/contents/tree_traversal/code/java/Tree.java @@ -1,4 +1,3 @@ -// submitted by xam4lor import java.util.ArrayList; import java.util.PriorityQueue; import java.util.Queue; @@ -45,19 +44,22 @@ public void dfsRecursiveInOrderBinary() { dfsRecursiveInOrderBinary(this.root); } - // This assumes only 2 children private void dfsRecursiveInOrderBinary(Node node) { - if (node.children.size() > 2) { - System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!"); - return; - } - - if (node.children.size() > 1) { - dfsRecursiveInOrderBinary(node.children.get(0)); - System.out.println(node.id); - dfsRecursiveInOrderBinary(node.children.get(1)); - } else { - System.out.println(node.id); + switch (node.children.size()) { + case 2: + dfsRecursiveInOrderBinary(node.children.get(0)); + System.out.println(node.id); + dfsRecursiveInOrderBinary(node.children.get(1)); + break; + case 1: + dfsRecursiveInOrderBinary(node.children.get(0)); + System.out.println(node.id); + break; + case 0: + System.out.println(node.id); + break; + default: + System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!"); } } diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index e03f09652..557cfdb55 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -12,7 +12,7 @@ Trees are naturally recursive data structures, and because of this, we cannot ac {% sample lang="c" %} [import:7-11, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:110-126, lang:"java"](code/java/Tree.java) +[import:112-128, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:1-10, lang:"javascript"](code/javascript/tree.js) As a note, a `node` struct is not necessary in javascript, so this is an example of how a tree might be constructed. @@ -58,7 +58,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="c" %} [import:37-45, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:21-27, lang:"java"](code/java/Tree.java) +[import:20-26, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:12-15, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} @@ -112,7 +112,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="c" %} [import:47-53, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:34-41, lang:"java"](code/java/Tree.java) +[import:33-40, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:17-20, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} @@ -161,7 +161,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="c" %} [import:55-73, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:48-62, lang:"java"](code/java/Tree.java) +[import:47-64, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:22-34, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} @@ -219,7 +219,7 @@ In code, it looks like this: {% sample lang="c" %} [import:75-93, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:65-79, lang:"java"](code/java/Tree.java) +[import:67-81, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:36-43, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} @@ -270,7 +270,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="c" %} [import:95-113, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:81-95, lang:"java"](code/java/Tree.java) +[import:83-97, lang:"java"](code/java/Tree.java) {% sample lang="js" %} [import:45-52, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} From 0652a18791c8a3548c227d790361554a36084b00 Mon Sep 17 00:00:00 2001 From: Neverik Date: Sat, 23 Oct 2021 16:09:29 +0300 Subject: [PATCH 58/90] Tree traversal in smalltalk (#453) --- .../code/smalltalk/tree_traversal.st | 81 +++++++++++++++++++ contents/tree_traversal/tree_traversal.md | 14 ++++ 2 files changed, 95 insertions(+) create mode 100644 contents/tree_traversal/code/smalltalk/tree_traversal.st diff --git a/contents/tree_traversal/code/smalltalk/tree_traversal.st b/contents/tree_traversal/code/smalltalk/tree_traversal.st new file mode 100644 index 000000000..411e5ff45 --- /dev/null +++ b/contents/tree_traversal/code/smalltalk/tree_traversal.st @@ -0,0 +1,81 @@ +Object subclass: #Node + instanceVariableNames: 'children data' + classVariableNames: '' + package: '' + +Node>>children + "Children getter." + ^ children + +Node>>children: newChildren + "Children setter." + children := newChildren. + +Node>>data + "Data getter" + ^ data + +Node>>data: newData + "Data setter" + data := newData. + +Node>>dfsRecursive + "Recursive depth first search." + Transcript show: data; cr. + children collect: [ :child | child dfsRecursive ] + +Node>>dfsRecursivePostOrder + "Recursive depth first search (post-order)." + children collect: [ :child | (child dfsRecursivePostOrder)]. + Transcript show: data; cr. + +Node>>dfsInOrderBinaryTree + "Recursive depth first search on a binary tree in order." + children size > 2 ifTrue: [ + Transcript show: 'This is not a binary tree!'; cr. + ^self. + ]. + children size = 2 ifTrue: [ + (children at: 1) dfsInOrderBinaryTree: value. + ]. + Transcript show: data; cr. + children size >= 1 ifTrue: [ + (children at: 0) dfsInOrderBinaryTree: value. + ]. + ^self. + +Node>>dfsStack + "Depth-first search with a stack." + | stack top | + stack := Stack new. + stack push: self. + [stack size > 0] whileTrue: [ + top := stack pop. + Transcript show: (top data); cr. + top children reverseDo: [ :child | + stack push: child. + ]. + ]. + +Node>>bfs + "A breadth-first tree search using queues." + | queue current | + queue := LinkedList with: self. + [ queue size > 0 ] whileTrue: [ + current := queue first. + queue removeFirst. + Transcript show: (current data); cr. + current children collect: [ :child | + queue addLast: child + ]. + ]. + +| test | +test := Node new: 1 children: { Node new: 2. + Node new: 3 children: { Node new: 4. + Node new: 5. } }. +test dfsRecursive. +test dfsRecursivePostorder. +test dfsInOrderBinaryTree. +test dfsStack. +test bfs. diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index 557cfdb55..c287b7612 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -32,6 +32,8 @@ As a note, a `node` struct is not necessary in javascript, so this is an example [import:4-37, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:1-5, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:1-20, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:5-8, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -77,6 +79,8 @@ Because of this, the most straightforward way to traverse the tree might be recu [import:41-49, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:7-10, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:22-27, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:10-15, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -131,6 +135,8 @@ Now, in this case the first element searched through is still the root of the tr [import:51-57, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:12-15, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:29-34, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:17-22, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -180,6 +186,8 @@ In this case, the first node visited is at the bottom of the tree and moves up t [import:59-78, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:17-31, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:36-49, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:24-38, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -238,6 +246,8 @@ In code, it looks like this: [import:80-91, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:33-41, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:47-58, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:40-49, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -289,6 +299,8 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can [import:93-104, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:43-51, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import:60-71, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import:51-60, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} @@ -351,6 +363,8 @@ The code snippets were taken from this [Scratch project](https://scratch.mit.edu [import, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import, lang:"crystal"](code/crystal/tree-traversal.cr) +{% sample lang="st" %} +[import, lang:"smalltalk"](code/smalltalk/tree_traversal.st) {% sample lang="go" %} [import, lang:"go"](code/golang/treetraversal.go) {% sample lang="asm-x64" %} From f7e8e60dd6679bd1664e6c79e4b25b0be4589f15 Mon Sep 17 00:00:00 2001 From: PaddyKe <34421580+PaddyKe@users.noreply.github.com> Date: Sat, 23 Oct 2021 16:40:11 +0200 Subject: [PATCH 59/90] fixed print statements (#901) --- .../approximate_counting/code/c++/approximate_counting.cpp | 6 +++--- contents/approximate_counting/code/c/approximate_counting.c | 6 +++--- .../approximate_counting/code/julia/approximate_counting.jl | 6 +++--- .../code/python/approximate_counting.py | 6 +++--- 4 files changed, 12 insertions(+), 12 deletions(-) diff --git a/contents/approximate_counting/code/c++/approximate_counting.cpp b/contents/approximate_counting/code/c++/approximate_counting.cpp index 7f3f1a16c..53f4641af 100644 --- a/contents/approximate_counting/code/c++/approximate_counting.cpp +++ b/contents/approximate_counting/code/c++/approximate_counting.cpp @@ -61,11 +61,11 @@ auto test_approximate_count( int main() { std::cout << "Counting Tests, 100 trials\n"; - std::cout << "testing 1,000, a = 30, 1% error " + std::cout << "testing 1,000, a = 30, 10% error " << test_approximate_count(100, 1000, 30, 0.1) << "\n"; - std::cout << "testing 12,345, a = 10, 1% error " + std::cout << "testing 12,345, a = 10, 10% error " << test_approximate_count(100, 12345, 10, 0.1) << "\n"; // Note : with a lower a, we need more trials, so a higher % error here. - std::cout << "testing 222,222, a = 0.5, 10% error " + std::cout << "testing 222,222, a = 0.5, 20% error " << test_approximate_count(100, 222222, 0.5, 0.2) << "\n"; } diff --git a/contents/approximate_counting/code/c/approximate_counting.c b/contents/approximate_counting/code/c/approximate_counting.c index ded7a518e..da44334a7 100644 --- a/contents/approximate_counting/code/c/approximate_counting.c +++ b/contents/approximate_counting/code/c/approximate_counting.c @@ -71,11 +71,11 @@ int main() srand(time(NULL)); printf("Counting Tests, 100 trials\n"); - printf("testing 1000, a = 30, 1%% error\n"); + printf("testing 1000, a = 30, 10%% error\n"); test_approximation_count(100, 1000, 30, 0.1); - printf("testing 12345, a = 10, 1%% error\n"); + printf("testing 12345, a = 10, 10%% error\n"); test_approximation_count(100, 12345, 10, 0.1); - printf("testing 222222, a = 0.5, 10%% error\n"); + printf("testing 222222, a = 0.5, 20%% error\n"); test_approximation_count(100, 222222, 0.5, 0.2); return 0; diff --git a/contents/approximate_counting/code/julia/approximate_counting.jl b/contents/approximate_counting/code/julia/approximate_counting.jl index 36b07651e..c6cf3b223 100644 --- a/contents/approximate_counting/code/julia/approximate_counting.jl +++ b/contents/approximate_counting/code/julia/approximate_counting.jl @@ -51,11 +51,11 @@ function test_approximate_count(n_trials, n_items, a, threshold) end @testset "Counting Tests, 100 trials" begin - println("testing 1,000, a = 30, 1% error") + println("testing 1,000, a = 30, 10% error") test_approximate_count(100, 1000, 30, 0.1) - println("testing 12,345, a = 10, 1% error") + println("testing 12,345, a = 10, 10% error") test_approximate_count(100, 12345, 10, 0.1) # Note: with a lower a, we need more trials, so a higher % error here. - println("testing 222,222, a = 0.5, 10% error") + println("testing 222,222, a = 0.5, 20% error") test_approximate_count(100, 222222, 0.5, 0.2) end diff --git a/contents/approximate_counting/code/python/approximate_counting.py b/contents/approximate_counting/code/python/approximate_counting.py index eb31b2b24..0088debcc 100644 --- a/contents/approximate_counting/code/python/approximate_counting.py +++ b/contents/approximate_counting/code/python/approximate_counting.py @@ -41,9 +41,9 @@ def test_approximate_count(n_trials, n_items, a, threshold): if abs((avg - n_items)/n_items) < threshold: print("passed") -print("testing 1,000, a = 30, 1% error") +print("testing 1,000, a = 30, 10% error") test_approximate_count(100, 1000, 30, 0.1) -print("testing 12,345, a = 10, 1% error") +print("testing 12,345, a = 10, 10% error") test_approximate_count(100, 12345, 10, 0.1) -print("testing 222,222, a = 0.5, 10% error") +print("testing 222,222, a = 0.5, 20% error") test_approximate_count(100, 222222, 0.5, 0.2) From 0fa638134628ae1911b5461df92369f02d6644b6 Mon Sep 17 00:00:00 2001 From: Dimitri Belopopsky Date: Sat, 23 Oct 2021 17:12:18 +0200 Subject: [PATCH 60/90] Fixes in PATH that make dlang, emojicode and factor usable (#890) --- .devcontainer/Dockerfile | 28 ++++++++++++---------------- 1 file changed, 12 insertions(+), 16 deletions(-) diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index bc58ae358..18af4df12 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -31,11 +31,10 @@ RUN sudo sh -c 'sudo dpkg -i packages-microsoft-prod.deb' RUN sudo sh -c 'rm packages-microsoft-prod.deb' # Setup D Lang -RUN sudo sh -c 'mkdir -p ~/dlang && wget https://dlang.org/install.sh -O ~/dlang/install.sh' -RUN sudo sh -c 'bash ~/dlang/install.sh' -## From Docs not needed though -# RUN sudo sh -c 'source ~/dlang/dmd-2.097.2/activate' -ENV PATH=$PATH:/root/dlang/dmd-2.097.2/linux/bin64 +ENV DLANG_VERSION=2.097.2 +RUN mkdir -p ~/dlang && wget https://dlang.org/install.sh -O ~/dlang/install.sh +RUN bash ~/dlang/install.sh dmd-$DLANG_VERSION +ENV PATH=$PATH:~/dlang/dmd-$DLANG_VERSION/linux/bin64/ # Setup Go RUN sudo sh -c 'wget -c https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz -O - | sudo tar -xz -C /usr/local' @@ -56,17 +55,14 @@ ENV PATH=$PATH:/usr/local/kotlinc/bin # Setup Matlab # ?????? This is a licensed language??? -# Setup Emojicode (in progress) -RUN sudo sh -c 'wget -c https://github.com/emojicode/emojicode/releases/download/v1.0-beta.2/Emojicode-1.0-beta.2-Linux-x86_64.tar.gz -O /usr/local/Emojicode-1.0-beta.2-Linux-x86_64.tar.gz' -RUN sudo tar -xvzf /usr/local/Emojicode-1.0-beta.2-Linux-x86_64.tar.gz -# && cd ~/emojicode/ && echo && ./install.sh' -ENV PATH=$PATH:/usr/local/Emojicode-1.0-beta.2-Linux-x86_64 - -# Setup Factor (in progress) -RUN mkdir -p ~/factor && wget https://downloads.factorcode.org/releases/0.98/factor-linux-x86-64-0.98.tar.gz -O ~/factor/factor.tar.gz -RUN tar -xzf /root/factor/factor.tar.gz -# && rm ~/factor/factor.tar.gz -ENV PATH=$PATH:/root/factor/factor +# Setup Emojicode +RUN mkdir -p ~/emojicode && wget -c https://github.com/emojicode/emojicode/releases/download/v1.0-beta.2/Emojicode-1.0-beta.2-Linux-x86_64.tar.gz -O ~/emojicode/emojicode.tar.gz && \ + tar -xzf ~/emojicode/emojicode.tar.gz -C ~/emojicode --strip-components=1 +ENV PATH=$PATH:~/emojicode + +# Setup Factor +RUN mkdir -p ~/factor && wget https://downloads.factorcode.org/releases/0.98/factor-linux-x86-64-0.98.tar.gz -O ~/factor/factor.tar.gz && tar -xzf ~/factor/factor.tar.gz -C ~/factor --strip-components=1 +ENV PATH=$PATH:~/factor/factor # Setup R RUN sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys E298A3A825C0D65DFD57CBB651716619E084DAB9 From 44d8118d76223b90e1b53dfe37ae1fe7569c9a6b Mon Sep 17 00:00:00 2001 From: James Schloss Date: Sat, 23 Oct 2021 17:32:21 +0200 Subject: [PATCH 61/90] fixing huffman encoding for Julia and adding Test (#828) --- .../huffman_encoding/code/julia/huffman.jl | 39 ++++++++++++------- 1 file changed, 25 insertions(+), 14 deletions(-) diff --git a/contents/huffman_encoding/code/julia/huffman.jl b/contents/huffman_encoding/code/julia/huffman.jl index 593d4b4f8..e01fd1dfd 100644 --- a/contents/huffman_encoding/code/julia/huffman.jl +++ b/contents/huffman_encoding/code/julia/huffman.jl @@ -1,3 +1,5 @@ +using Test + # This is for the PriorityQueue using DataStructures @@ -13,8 +15,6 @@ struct Branch end const Node = Union{Leaf, Branch} -isbranch(branch::Branch) = true -isbranch(other::T) where {T} = false function codebook_recurse!(leaf::Leaf, code::String, dict::Dict{Char,String}) @@ -33,7 +33,11 @@ end # This outputs encoding Dict to be used for encoding function create_codebook(n::Node) codebook = Dict{Char,String}() - codebook_recurse!(n, "", codebook) + if isa(n, Leaf) + codebook[n.key]="0" + else + codebook_recurse!(n, "", codebook) + end return codebook end @@ -85,14 +89,19 @@ function decode(huffman_tree::Node, bitstring::String) current = huffman_tree final_string = "" for i in bitstring - if (i == '1') - current = current.left + if isa(huffman_tree, Branch) + if (i == '1') + current = current.left + else + current = current.right + end + + if (!isa(current, Branch)) + final_string *= string(current.key) + current = huffman_tree + end else - current = current.right - end - if (!isbranch(current)) - final_string = final_string * string(current.key) - current = huffman_tree + final_string *= string(huffman_tree.key) end end @@ -102,11 +111,13 @@ end function two_pass_huffman(phrase::String) huffman_tree = create_tree(phrase) codebook = create_codebook(huffman_tree) - println(codebook) bitstring = encode(codebook, phrase) final_string = decode(huffman_tree, bitstring) - println(bitstring) - println(final_string) + return final_string end -two_pass_huffman("bibbity bobbity") +@testset "b-string tests" begin + @test two_pass_huffman("b") == "b" + @test two_pass_huffman("bbbbbbbb") == "bbbbbbbb" + @test two_pass_huffman("bibbity bobbity") == "bibbity bobbity" +end From cf56e67900a253a49cb8d98e595422493ca9a91c Mon Sep 17 00:00:00 2001 From: Henrik Christensen Date: Sat, 23 Oct 2021 22:06:45 +0200 Subject: [PATCH 62/90] JavaScript tree traversal: updated dfsInorder (#902) --- CONTRIBUTORS.md | 1 + .../tree_traversal/code/javascript/tree.js | 29 +++++++++++++++---- contents/tree_traversal/tree_traversal.md | 10 +++---- 3 files changed, 29 insertions(+), 11 deletions(-) diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index e3707e290..9b2c1b460 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -60,3 +60,4 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Ridham177 - Hugo Salou - Dimitri Belopopsky ++ Henrik Abel Christensen diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index b6705bfdd..6670fe739 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -10,11 +10,19 @@ function createTree(rows, children) { } function dfsPreorder(tree) { + if (!tree) { + return; + } + console.log(tree.id); tree.children.forEach(dfsPreorder); } function dfsPostorder(tree) { + if (!tree) { + return; + } + tree.children.forEach(dfsPostorder); console.log(tree.id); } @@ -24,13 +32,22 @@ function dfsInorder(tree) { return; } - if (tree.children.length > 2) { - throw new Error("Postorder traversal is only valid for binary trees"); + switch (tree.children.length) { + case 2: + dfsInorder(tree.children[0]); + console.log(tree.id); + dfsInorder(tree.children[1]); + break; + case 1: + dfsInorder(tree.children[0]); + console.log(tree.id); + break; + case 0: + console.log(tree.id); + break; + default: + throw new Error("Postorder traversal is only valid for binary trees"); } - - dfsInorder(tree.children[0]); - console.log(tree.id); - dfsInorder(tree.children[1]); } function dfsIterative(tree) { diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index c287b7612..6d6504760 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -62,7 +62,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="java" %} [import:20-26, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:12-15, lang:"javascript"](code/javascript/tree.js) +[import:12-19, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} [import:18-23, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} @@ -118,7 +118,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="java" %} [import:33-40, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:17-20, lang:"javascript"](code/javascript/tree.js) +[import:21-28, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} [import:26-31, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} @@ -169,7 +169,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="java" %} [import:47-64, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:22-34, lang:"javascript"](code/javascript/tree.js) +[import:30-51, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} [import:34-46, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} @@ -229,7 +229,7 @@ In code, it looks like this: {% sample lang="java" %} [import:67-81, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:36-43, lang:"javascript"](code/javascript/tree.js) +[import:53-60, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} [import:49-60, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} @@ -282,7 +282,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="java" %} [import:83-97, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:45-52, lang:"javascript"](code/javascript/tree.js) +[import:62-69, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} [import:63-75, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} From 3358b378da4031ace4af10d7999807e45296ed81 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sun, 24 Oct 2021 02:24:59 +0530 Subject: [PATCH 63/90] julia: change printf to print --- contents/tree_traversal/code/julia/Tree.jl | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index abc207074..7382fdad0 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -8,7 +8,7 @@ end function DFS_recursive(n::Node) # Here we are doing something... - @printf("%i ", n.ID) + print(n.ID, " ") for child in n.children DFS_recursive(child) @@ -22,7 +22,7 @@ function DFS_recursive_postorder(n::Node) end # Here we are doing something... - @printf("%i ", n.ID) + print(n.ID, " ") end # This assumes only 2 children, but accounts for other possibilities @@ -30,13 +30,13 @@ function DFS_recursive_inorder_btree(n::Node) if (length(n.children) == 2) DFS_recursive_inorder_btree(n.children[1]) - @printf("%i ", n.ID) + print(n.ID, " ") DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - @printf("%i ", n.ID) + print(n.ID, " ") elseif (length(n.children) == 0) - @printf("%i ", n.ID) + print(n.ID, " ") else println("Not a binary tree!") end @@ -47,7 +47,7 @@ function DFS_stack(n::Node) push!(s, n) while(length(s) > 0) - @printf("%i ", top(s).ID) + print(top(s).ID, " ") temp = pop!(s) for child in temp.children push!(s, child) @@ -60,7 +60,7 @@ function BFS_queue(n::Node) enqueue!(q, n) while(length(q) > 0) - @printf("%i ", first(q).ID) + print(first(q).ID, " ") temp = dequeue!(q) for child in temp.children enqueue!(q, child) From 2cb788285340868db8382bbe665d7471f7869bd2 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 21:04:27 +0530 Subject: [PATCH 64/90] pep8ify python --- .../code/python/Tree_example.py | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/contents/tree_traversal/code/python/Tree_example.py b/contents/tree_traversal/code/python/Tree_example.py index 67dd516a3..94cbce35c 100644 --- a/contents/tree_traversal/code/python/Tree_example.py +++ b/contents/tree_traversal/code/python/Tree_example.py @@ -15,30 +15,30 @@ def create_tree(node, num_row, num_child): return node -def DFS_recursive(node): +def dfs_recursive(node): if node.data != None: print(node.data) for child in node.children: - DFS_recursive(child) + dfs_recursive(child) -def DFS_recursive_postorder(node): +def dfs_recursive_postorder(node): for child in node.children: - DFS_recursive_postorder(child) + dfs_recursive_postorder(child) if node.data != None: print(node.data) # This assumes only 2 children, but accounts for other possibilities -def DFS_recursive_inorder_btree(node): +def dfs_recursive_inorder_btree(node): if (len(node.children) == 2): - DFS_recursive_inorder_btree(node.children[0]) + dfs_recursive_inorder_btree(node.children[0]) print(node.data) - DFS_recursive_inorder_btree(node.children[1]) + dfs_recursive_inorder_btree(node.children[1]) elif (len(node.children) == 1): - DFS_recursive_inorder_btree(node.children[0]) + dfs_recursive_inorder_btree(node.children[0]) print(node.data) elif (len(node.children) == 0): print(node.data) @@ -46,7 +46,7 @@ def DFS_recursive_inorder_btree(node): print("Not a binary tree!") -def DFS_stack(node): +def dfs_stack(node): stack = [] stack.append(node) @@ -60,7 +60,7 @@ def DFS_stack(node): stack.append(child) -def BFS_queue(node): +def bfs_queue(node): queue = [] queue.append(node) @@ -78,21 +78,21 @@ def main(): tree = create_tree(Node(), 3, 3) print("Recursive:") - DFS_recursive(tree) + dfs_recursive(tree) print("Recursive Postorder:") - DFS_recursive_postorder(tree) + dfs_recursive_postorder(tree) print("Stack:") - DFS_stack(tree) + dfs_stack(tree) print("Queue:") - BFS_queue(tree) + bfs_queue(tree) - binaryTree = create_tree(Node(), 3, 2) + binary_tree = create_tree(Node(), 3, 2) print("Recursive Inorder Binary Tree:") - DFS_recursive_inorder_btree(binaryTree) + dfs_recursive_inorder_btree(binary_tree) if __name__ == '__main__': main() From 69cd00160aa9cce7c59cf3ddbcd5d1bf654a76fc Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 21:15:25 +0530 Subject: [PATCH 65/90] rename Tree_example.py --- .../code/python/{Tree_example.py => tree_traversal.py} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename contents/tree_traversal/code/python/{Tree_example.py => tree_traversal.py} (100%) diff --git a/contents/tree_traversal/code/python/Tree_example.py b/contents/tree_traversal/code/python/tree_traversal.py similarity index 100% rename from contents/tree_traversal/code/python/Tree_example.py rename to contents/tree_traversal/code/python/tree_traversal.py From e4c8ff1d61db1ab4c0744fbaefac1cab80fbd30b Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Fri, 3 Sep 2021 22:45:07 +0530 Subject: [PATCH 66/90] standardize python output --- .../code/python/tree_traversal.py | 38 ++++++++++--------- 1 file changed, 21 insertions(+), 17 deletions(-) diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py index 94cbce35c..98dad806d 100644 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -3,7 +3,6 @@ def __init__(self): self.data = None self.children = [] - def create_tree(node, num_row, num_child): node.data = num_row @@ -17,7 +16,7 @@ def create_tree(node, num_row, num_child): def dfs_recursive(node): if node.data != None: - print(node.data) + print(node.data, end=' ') for child in node.children: dfs_recursive(child) @@ -28,20 +27,20 @@ def dfs_recursive_postorder(node): dfs_recursive_postorder(child) if node.data != None: - print(node.data) + print(node.data, end=' ') # This assumes only 2 children, but accounts for other possibilities def dfs_recursive_inorder_btree(node): - if (len(node.children) == 2): + if len(node.children) == 2: dfs_recursive_inorder_btree(node.children[0]) - print(node.data) + print(node.data, end=' ') dfs_recursive_inorder_btree(node.children[1]) - elif (len(node.children) == 1): + elif len(node.children) == 1: dfs_recursive_inorder_btree(node.children[0]) - print(node.data) - elif (len(node.children) == 0): - print(node.data) + print(node.data, end=' ') + elif len(node.children) == 0: + print(node.data, end=' ') else: print("Not a binary tree!") @@ -53,7 +52,7 @@ def dfs_stack(node): temp = None while len(stack) > 0: - print(stack[-1].data) + print(stack[-1].data, end=' ') temp = stack.pop() for child in temp.children: @@ -67,7 +66,7 @@ def bfs_queue(node): temp = None while len(queue) > 0: - print(queue[0].data) + print(queue[0].data, end=' ') temp = queue.pop(0) for child in temp.children: @@ -75,24 +74,29 @@ def bfs_queue(node): def main(): - tree = create_tree(Node(), 3, 3) + tree = create_tree(Node(), 2, 3) - print("Recursive:") + print("[#] Recursive DFS:") dfs_recursive(tree) + print() - print("Recursive Postorder:") + print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) + print() - print("Stack:") + print("[#] Stack-based DFS :") dfs_stack(tree) + print() - print("Queue:") + print("[#] Queue-based BFS:") bfs_queue(tree) + print() binary_tree = create_tree(Node(), 3, 2) - print("Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder Binary Tree:") dfs_recursive_inorder_btree(binary_tree) + print() if __name__ == '__main__': main() From 79d8b68c38c91b4c6be6e3f25113611ed2b1c64d Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:28:04 +0530 Subject: [PATCH 67/90] standardize c output --- .../tree_traversal/code/c/tree_traversal.c | 39 ++++++++++++++----- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index 7fed9a16c..3c1db527b 100644 --- a/contents/tree_traversal/code/c/tree_traversal.c +++ b/contents/tree_traversal/code/c/tree_traversal.c @@ -35,7 +35,7 @@ void destroy_tree(struct node n) { } void dfs_recursive(struct node n) { - printf("%d\n", n.id); + printf("%d ", n.id); if (n.children) { for (size_t i = 0; i < n.children_size; ++i) { @@ -49,22 +49,22 @@ void dfs_recursive_postorder(struct node n) { dfs_recursive_postorder(n.children[i]); } - printf("%d\n", n.id); + printf("%d ", n.id); } void dfs_recursive_inorder_btree(struct node n) { switch (n.children_size) { case 2: dfs_recursive_inorder_btree(n.children[0]); - printf("%d\n", n.id); + printf("%d ", n.id); dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - printf("%d\n", n.id); + printf("%d ", n.id); break; case 0: - printf("%d\n", n.id); + printf("%d ", n.id); break; default: printf("This is not a binary tree.\n"); @@ -83,7 +83,7 @@ void dfs_stack(struct node n) { break; } - printf("%d\n", tmp->id); + printf("%d ", tmp->id); for (size_t i = 0; i < tmp->children_size; ++i) { stack_push(&stk, &tmp->children[i]); } @@ -103,7 +103,7 @@ void bfs_queue(struct node n) { break; } - printf("%d\n", tmp->id); + printf("%d ", tmp->id); for (size_t i = 0; i < tmp->children_size; ++i) { enqueue(&q, &tmp->children[i]); } @@ -113,9 +113,30 @@ void bfs_queue(struct node n) { } int main() { - struct node root = create_tree(3, 3); + struct node root = create_tree(2, 3); + + printf("[#] Recursive DFS:\n"); + dfs_recursive(root); + printf("\n"); + + printf("[#] Recursive Postorder DFS:\n"); + dfs_recursive_postorder(root); + printf("\n"); + + printf("[#] Stack-based DFS:\n"); + dfs_stack(root); + printf("\n"); + + printf("[#] Queue-based BFS:\n"); bfs_queue(root); + printf("\n"); + destroy_tree(root); + struct node root_binary = create_tree(3, 2); + printf("[#] Recursive Inorder DFS for Binary Tree:\n"); + dfs_recursive_inorder_btree(root_binary); + printf("\n"); + + destroy_tree(root_binary); return 0; -} From 2d5f36eeb4651ddbd488b9552a15017b60aeaee8 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:35:12 +0530 Subject: [PATCH 68/90] standardize c++ output --- .../tree_traversal/code/c++/tree_example.cpp | 33 +++++++++++-------- 1 file changed, 19 insertions(+), 14 deletions(-) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index 9f2dd80e1..d109f11e5 100644 --- a/contents/tree_traversal/code/c++/tree_example.cpp +++ b/contents/tree_traversal/code/c++/tree_example.cpp @@ -17,7 +17,7 @@ struct node { // Simple recursive scheme for DFS void dfs_recursive(node const& n) { // Here we are doing something... - std::cout << n.value << '\n'; + std::cout << n.value << ' '; for (auto const& child : n.children) { dfs_recursive(child); } @@ -27,7 +27,7 @@ void dfs_recursive_postorder(node const& n) { for (auto const& child : n.children) { dfs_recursive_postorder(child); } - std::cout << n.value << '\n'; + std::cout << n.value << ' '; } @@ -35,15 +35,15 @@ void dfs_recursive_inorder_btree(node const& n) { switch (n.children.size()) { case 2: dfs_recursive_inorder_btree(n.children[0]); - std::cout << n.value << '\n'; + std::cout << n.value << ' '; dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - std::cout << n.value << '\n'; + std::cout << n.value << ' '; break; case 0: - std::cout << n.value << '\n'; + std::cout << n.value << ' '; break; default: std::cout << "This is not a binary tree.\n"; @@ -61,7 +61,7 @@ void dfs_stack(node const& n) { while (stack.size() > 0) { auto const& temp = *stack.top(); stack.pop(); - std::cout << temp.value << '\n'; + std::cout << temp.value << ' '; for (auto const& child : temp.children) { stack.push(&child); @@ -78,7 +78,7 @@ void bfs_queue(node const& n) { auto const& temp = *queue.front(); queue.pop(); - std::cout << temp.value << '\n'; + std::cout << temp.value << ' '; for (auto const& child : temp.children) { queue.push(&child); } @@ -100,18 +100,23 @@ node create_tree(size_t num_row, size_t num_child) { int main() { // Creating Tree in main - auto root = create_tree(3, 3); + auto root = create_tree(2, 3); auto binary_root = create_tree(3, 2); - std::cout << "DFS recursive:\n"; + std::cout << "[#] Recursive DFS:\n"; dfs_recursive(root); - std::cout << "DFS post order recursive:\n"; + std::cout << '\n'; + std::cout << "[#] Recursive Postorder DFS:\n"; dfs_recursive_postorder(root); - std::cout << "DFS inorder binary tree:\n"; - dfs_recursive_inorder_btree(binary_root); - std::cout << "DFS stack:\n"; + std::cout << '\n'; + std::cout << "[#] Stack-based DFS:\n"; dfs_stack(root); - std::cout << "BFS queue:\n"; + std::cout << '\n'; + std::cout << "[#] Queue-based BFS:\n"; bfs_queue(root); + std::cout << '\n'; + std::cout << "[#] Recursive Inorder DFS for Binary Tree:\n"; + dfs_recursive_inorder_btree(binary_root); + std::cout << '\n'; return 0; } From 4989ad8a184393072dfed4e3c6453d2e89351369 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:41:40 +0530 Subject: [PATCH 69/90] standardize rust output --- contents/tree_traversal/code/rust/tree.rs | 35 +++++++++++++---------- 1 file changed, 20 insertions(+), 15 deletions(-) diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index f281e1a8c..35319454a 100644 --- a/contents/tree_traversal/code/rust/tree.rs +++ b/contents/tree_traversal/code/rust/tree.rs @@ -7,7 +7,7 @@ struct Node { } fn dfs_recursive(n: &Node) { - println!("{}", n.value); + print!("{} ", n.value); for child in &n.children { dfs_recursive(child); @@ -19,22 +19,22 @@ fn dfs_recursive_postorder(n: &Node) { dfs_recursive_postorder(child); } - println!("{}", n.value); + print!("{} ", n.value); } fn dfs_recursive_inorder_btree(n: &Node) { match &n.children[..] { [left, right] => { dfs_recursive_inorder_btree(left); - println!("{}", n.value); + print!("{} ", n.value); dfs_recursive_inorder_btree(right); } [left] => { dfs_recursive_inorder_btree(left); - println!("{}", n.value); + print!("{} ", n.value); } - [] => println!("{}", n.value), - _ => println!("This is not a binary tree."), + [] => print!("{} ", n.value), + _ => print!("This is not a binary tree. "), } } @@ -42,7 +42,7 @@ fn dfs_stack(n: &Node) { let mut stack = vec![n]; while let Some(current) = stack.pop() { - println!("{}", current.value); + print!("{} ", current.value); stack.extend(¤t.children); } } @@ -52,7 +52,7 @@ fn bfs_queue(n: &Node) { queue.push_back(n); while let Some(current) = queue.pop_front() { - println!("{}", current.value); + print!("{} ", current.value); queue.extend(¤t.children); } } @@ -78,19 +78,24 @@ fn create_tree(num_row: u64, num_child: u64) -> Node { fn main() { let root = create_tree(2, 3); - println!("Recursive DFS:"); + println!("[#] Recursive DFS:"); dfs_recursive(&root); + println!(); - println!("Stack DFS:"); + println!("[#] Recursive Postorder DFS:"); + dfs_recursive_postorder(&root); + println!(); + + println!("[#] Stack-based DFS:"); dfs_stack(&root); + println!(); - println!("Queue BFS:"); + println!("[#] Queue-based BFS:"); bfs_queue(&root); + println!(); - println!("Recursive post-order DFS:"); - dfs_recursive_postorder(&root); - - println!("Recursive in-order DFS BTree:"); + println!("[#] Recursive Inorder DFS for Binary Tree:"); let root_binary = create_tree(3, 2); dfs_recursive_inorder_btree(&root_binary); + println!(); } From 20cda9964d4466dd498db106a07b5d1e9be8226e Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 00:48:43 +0530 Subject: [PATCH 70/90] standardize javascript output Resolved conflict with master (by Amaras) --- .../tree_traversal/code/javascript/tree.js | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index 6670fe739..13c4ff7a6 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -14,7 +14,7 @@ function dfsPreorder(tree) { return; } - console.log(tree.id); + process.stdout.write(tree.id + " "); tree.children.forEach(dfsPreorder); } @@ -24,7 +24,7 @@ function dfsPostorder(tree) { } tree.children.forEach(dfsPostorder); - console.log(tree.id); + process.stdout.write(tree.id + " "); } function dfsInorder(tree) { @@ -54,7 +54,7 @@ function dfsIterative(tree) { const stack = [tree]; while (stack.length > 0) { const current = stack.pop(); - console.log(current.id); + process.stdout.write(current.id + " "); stack.push(...current.children); } } @@ -63,13 +63,26 @@ function bfs(tree) { const queue = [tree]; while (queue.length > 0) { const current = queue.shift(); - console.log(current.id); + process.stdout.write(current.id + " "); queue.push(...current.children); } } -const root = createTree(3, 3); +const root = createTree(2, 3); +console.log("[#] Recursive DFS:"); dfsPreorder(root); +console.log(); +console.log("[#] Recursive Postorder DFS:"); dfsPostorder(root); +console.log(); +console.log("[#] Stack-based DFS:"); dfsIterative(root); +console.log(); +console.log("[#] Queue-based BFS:"); bfs(root); +console.log(); +const root_binary = createTree(3, 2); +console.log("[#] Recursive Inorder DFS for Binary Tree:"); +dfsInorder(root_binary); +console.log(); + From 236685d5e166a04e71882f19374a3f4dff94d039 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 01:04:52 +0530 Subject: [PATCH 71/90] standardize julia output Resolved conflict with master (by Amaras) --- contents/tree_traversal/code/julia/Tree.jl | 34 ++++++++++++---------- 1 file changed, 18 insertions(+), 16 deletions(-) diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index d44345e8d..652048c71 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -1,4 +1,4 @@ -using DataStructures +using DataStructures, Printf struct Node children::Vector{Node} @@ -8,7 +8,7 @@ end function DFS_recursive(n::Node) # Here we are doing something... - println(n.ID) + @printf("%i ", n.ID) for child in n.children DFS_recursive(child) @@ -22,7 +22,7 @@ function DFS_recursive_postorder(n::Node) end # Here we are doing something... - println(n.ID) + @printf("%i ", n.ID) end # This assumes only 2 children, but accounts for other possibilities @@ -30,13 +30,13 @@ function DFS_recursive_inorder_btree(n::Node) if (length(n.children) == 2) DFS_recursive_inorder_btree(n.children[1]) - println(n.ID) + @printf("%i ", n.ID) DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - println(n.ID) + @printf("%i ", n.ID) elseif (length(n.children) == 0) - println(n.ID) + @printf("%i ", n.ID) else println("Not a binary tree!") end @@ -47,7 +47,7 @@ function DFS_stack(n::Node) push!(s, n) while(length(s) > 0) - println(first(s).ID) + @printf("%i ", top(s).ID) temp = pop!(s) for child in temp.children push!(s, child) @@ -60,7 +60,7 @@ function BFS_queue(n::Node) enqueue!(q, n) while(length(q) > 0) - println(first(q).ID) + @printf("%i ", first(q).ID) temp = dequeue!(q) for child in temp.children enqueue!(q, child) @@ -84,26 +84,28 @@ function create_tree(num_row::Int64, num_child::Int64) end function main() - - println("Creating Tree") root = create_tree(2, 3) - println("Using recursive DFS:") + println("[#] Recursive DFS:") DFS_recursive(root); + println() - println("Using recursive DFS with post-order traversal:") + println("[#] Recursive Postorder DFS:") DFS_recursive_postorder(root); + println() - println("Using stack-based DFS:") + println("[#] Stack-based DFS:") DFS_stack(root); + println() - println("Using queue-based BFS:") + println("[#] Queue-based BFS:") BFS_queue(root); + println() - println("Creating binary tree to test in-order traversal.") root_binary = create_tree(3,2) - println("Using In-order DFS:") + println("[#] Recursive Inorder DFS for Binary Tree:") DFS_recursive_inorder_btree(root_binary) + println() end main() From 6251005710f5db0daac66e2fd530365bd497d717 Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Fri, 3 Sep 2021 23:25:28 +0200 Subject: [PATCH 72/90] Standardized Coconut output --- .../tree_traversal/code/coconut/tree_traversal.coco | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index c7433fea2..077ea2e35 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -62,22 +62,22 @@ if __name__ =='__main__': tree = create_tree(3, 3) # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("Recursive DFS:") + print("[#] Recursive DFS:") dfs_recursive(tree) print() # Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 - print("Recursive Postorder DFS:") + print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) print() # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("Stack (DFS):") + print("[#] Stack (DFS):") dfs_stack(tree) print() # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 - print("Queue (BFS):") + print([#] "Queue (BFS):") bfs_queue(tree) print() @@ -85,7 +85,7 @@ if __name__ =='__main__': binary_tree = create_tree(3, 2) # Should print: 1 2 1 3 1 2 1 - print("Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From bf6c74bf23e3a2727ef6a3c6a433ad7cf53ba9b3 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:00:02 +0530 Subject: [PATCH 73/90] fix coconut --- .../tree_traversal/code/coconut/tree_traversal.coco | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index 077ea2e35..ad7be7932 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -50,8 +50,8 @@ def bfs_queue(node is Node): def create_tree(num_rows, num_child): """Creates a simple tree, where every node has 'num_child' children and is 'num_rows' deep.""" - if num_rows == 1: - return Node(1, ()) + if num_rows == 0: + return Node(0, ()) else: return Node(num_rows, tuple(create_tree(num_rows-1, num_child) for _ in range(num_child))) @@ -59,7 +59,7 @@ def create_tree(num_rows, num_child): if __name__ =='__main__': # A ternary tree for testing - tree = create_tree(3, 3) + tree = create_tree(2, 3) # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Recursive DFS:") @@ -72,12 +72,12 @@ if __name__ =='__main__': print() # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 - print("[#] Stack (DFS):") + print("[#] Stack-based DFS:") dfs_stack(tree) print() # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 - print([#] "Queue (BFS):") + print("[#] Queue-based BFS:") bfs_queue(tree) print() @@ -85,7 +85,7 @@ if __name__ =='__main__': binary_tree = create_tree(3, 2) # Should print: 1 2 1 3 1 2 1 - print("[#] Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From 14f9275277b6181a50cab2bb988cb28129142149 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:12:33 +0530 Subject: [PATCH 74/90] standardize go output --- .../code/golang/treetraversal.go | 38 ++++++++++++------- 1 file changed, 24 insertions(+), 14 deletions(-) diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index 548f552f7..deba1347d 100644 --- a/contents/tree_traversal/code/golang/treetraversal.go +++ b/contents/tree_traversal/code/golang/treetraversal.go @@ -8,7 +8,7 @@ type node struct { } func dfsRecursive(n *node) { - fmt.Println(n.id) + fmt.Printf("%d ", n.id) for _, child := range n.children { dfsRecursive(child) } @@ -18,20 +18,20 @@ func dfsRecursivePostorder(n *node) { for _, child := range n.children { dfsRecursive(child) } - fmt.Println(n.id) + fmt.Printf("%d ", n.id) } func dfsRecursiveInorderBtree(n *node) { switch len(n.children) { case 2: dfsRecursiveInorderBtree(n.children[0]) - fmt.Println(n.id) + fmt.Printf("%d ", n.id) dfsRecursiveInorderBtree(n.children[1]) case 1: dfsRecursiveInorderBtree(n.children[0]) - fmt.Println(n.id) + fmt.Printf("%d ", n.id) case 0: - fmt.Println(n.id) + fmt.Printf("%d ", n.id) default: fmt.Println("This is not a binary tree") } @@ -43,7 +43,7 @@ func dfsStack(n *node) { for len(stack) > 0 { cur := stack[0] stack = stack[1:] - fmt.Println(cur.id) + fmt.Printf("%d ", cur.id) stack = append(cur.children, stack...) } } @@ -54,7 +54,7 @@ func bfsQueue(n *node) { for len(queue) > 0 { cur := queue[0] queue = queue[1:] - fmt.Println(cur.id) + fmt.Printf("%d ", cur.id) queue = append(queue, cur.children...) } } @@ -74,17 +74,27 @@ func createTree(numRow, numChild int) *node { } func main() { - root := createTree(3, 3) + root := createTree(2, 3) binTree := createTree(3, 2) - fmt.Println("DFS recursive:") + fmt.Println("[#] DFS Recursive:") dfsRecursive(root) - fmt.Println("DFS post order recursive:") + fmt.Println() + + fmt.Println("[#] DFS Postorder Recursive:") dfsRecursivePostorder(root) - fmt.Println("DFS inorder binary tree:") - dfsRecursiveInorderBtree(binTree) - fmt.Println("DFS stack:") + fmt.Println() + + fmt.Println("[#] Stack-based DFS:") dfsStack(root) - fmt.Println("BFS queue:") + fmt.Println() + + fmt.Println("[#] Queue-based BFS:") bfsQueue(root) + fmt.Println() + + fmt.Println("[#] DFS Inorder for Binary Tree:") + dfsRecursiveInorderBtree(binTree) + fmt.Println() + } From 1103d8c33becdbb9a73ba24d2f6f793a4e62aabc Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 05:25:51 +0530 Subject: [PATCH 75/90] standardize common lisp output --- .../code/clisp/tree-traversal.lisp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 417a6f242..31395f3ac 100644 --- a/contents/tree_traversal/code/clisp/tree-traversal.lisp +++ b/contents/tree_traversal/code/clisp/tree-traversal.lisp @@ -58,36 +58,41 @@ (defun make-tree (num-rows num-child) "Creates a simple tree, where every node has 'num-child' children and is 'num-rows' deep." ;; A tree with 0 rows can't be created. - (if (eql num-rows 1) + (if (eql num-rows 0) (make-node - :data 1 + :data 0 :children nil) (make-node :data num-rows :children (loop repeat num-child collect (make-tree (1- num-rows) num-child))))) ;; A tree for testing -(defvar tree (make-tree 3 3)) +(defvar tree (make-tree 2 3)) ;; A binary tree for testing (defvar binary-tree (make-tree 3 2)) ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 +(format t "[#] Recursive DFS:~%") (dfs-recursive tree) (format t "~%") ;; Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 +(format t "[#] Recursive Postorder DFS:~%") (dfs-recursive-postorder tree) (format t "~%") -;; Should print: 1 2 1 3 1 2 1 -(dfs-recursive-inorder-btree binary-tree) -(format t "~%") - ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 +(format t "[#] Stack-based DFS:~%") (dfs-stack tree) (format t "~%") ;; Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 +(format t "[#] Queue-based BFS:~%") (bfs-queue tree) (format t "~%") + +;; Should print: 1 2 1 3 1 2 1 +(format t "[#] Recursive Inorder DFS for Binary Tree:~%") +(dfs-recursive-inorder-btree binary-tree) +(format t "~%") From ed09f86d1b8ad7e585fe59cd20e1798fe4a48328 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 11:59:11 +0530 Subject: [PATCH 76/90] standardize php output --- .../code/php/tree_traversal.php | 44 +++++++++---------- 1 file changed, 22 insertions(+), 22 deletions(-) diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index fde55046a..0951cea79 100644 --- a/contents/tree_traversal/code/php/tree_traversal.php +++ b/contents/tree_traversal/code/php/tree_traversal.php @@ -40,9 +40,7 @@ class TreeTraversal { public static function DFSRecursive(Tree $tree): void { - if ($tree->getId()) { - echo $tree->getId() . PHP_EOL; - } + echo $tree->getId() . ' '; foreach ($tree->getChildren() as $child) { static::DFSRecursive($child); } @@ -53,7 +51,7 @@ public static function DFSRecursivePostorder(Tree $tree): void foreach ($tree->getChildren() as $child) { static::DFSRecursivePostorder($child); } - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; } public static function DFSRecursiveInorderBinary(Tree $tree): void @@ -61,15 +59,15 @@ public static function DFSRecursiveInorderBinary(Tree $tree): void switch (count($tree->getChildren())) { case 2: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; static::DFSRecursiveInorderBinary($tree->getChildren()[1]); break; case 1: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; break; case 0: - echo $tree->getId() . PHP_EOL; + echo $tree->getId() . ' '; break; default: throw new InvalidArgumentException('Not a binary tree!'); @@ -83,7 +81,7 @@ public static function DFSStack(Tree $tree): void $temp = null; while (null !== ($temp = array_pop($stack))) { - echo $temp->getId() . PHP_EOL; + echo $temp->getId() . ' '; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -96,7 +94,7 @@ public static function DFSQueue(Tree $tree): void $temp = null; while (null !== ($temp = array_shift($stack))) { - echo $temp->getId() . PHP_EOL; + echo $temp->getId() . ' '; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -104,16 +102,13 @@ public static function DFSQueue(Tree $tree): void } } -function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree +function generate_tree(int $numOfRows, int $numOfChildren): Tree { - if ($id === -1) { - $id = 1; - } - $node = new Tree($id); + $node = new Tree($numOfRows); - if ($numOfRows > 1) { + if ($numOfRows > 0) { for ($i = 0; $i < $numOfChildren; $i++) { - $child = generate_tree($numOfRows - 1, $numOfChildren, $id * 10 + $i + 1); + $child = generate_tree($numOfRows - 1, $numOfChildren); $node->addChild($child); } } @@ -121,23 +116,28 @@ function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree return $node; } -$node = generate_tree(3, 3); +$node = generate_tree(2, 3); -echo 'DFS Recursive:' . PHP_EOL; +echo '[#] Recursive DFS:' . PHP_EOL; TreeTraversal::DFSRecursive($node); +echo PHP_EOL; -echo 'DFS Recursive Postorder:' . PHP_EOL; +echo '[#] Recursive Postorder DFS:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); +echo PHP_EOL; -echo 'DFS Stack:' . PHP_EOL; +echo '[#] Stack-based DFS:' . PHP_EOL; TreeTraversal::DFSStack($node); +echo PHP_EOL; -echo 'DFS Queue:' . PHP_EOL; +echo '[#] Queue-based BFS:' . PHP_EOL; TreeTraversal::DFSQueue($node); +echo PHP_EOL; // If you want to try to run binary order on a non-binary tree, // comment out the generation of the new tree below. // If you do that, an exception will be thrown $node = generate_tree(3, 2); -echo 'DFS Recursive Inorder Binary:' . PHP_EOL; +echo '[#] Recursive Inorder DFS for Binary Tree:' . PHP_EOL; TreeTraversal::DFSRecursiveInorderBinary($node); +echo PHP_EOL; From e792364b0bff297d5e59274925f6b43ea9d618f6 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sat, 4 Sep 2021 12:14:47 +0530 Subject: [PATCH 77/90] standardize swift output --- contents/tree_traversal/code/swift/tree.swift | 31 +++++++++++-------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/contents/tree_traversal/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index e286c8fb0..86e561435 100644 --- a/contents/tree_traversal/code/swift/tree.swift +++ b/contents/tree_traversal/code/swift/tree.swift @@ -22,7 +22,7 @@ func createTree(numRows: Int, numChildren: Int) -> Node { } func dfsRecursive(node: Node) { - print(node.value) + print(node.value, terminator:" ") for child in node.children! { dfsRecursive(node: child) @@ -34,19 +34,19 @@ func dfsRecursivePostOrder(node: Node) { dfsRecursivePostOrder(node: child) } - print(node.value) + print(node.value, terminator:" ") } func dfsRecursiveInOrderBinary(node: Node) { if node.children?.count == 2 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value) + print(node.value, terminator:" ") dfsRecursiveInOrderBinary(node: node.children![1]) } else if node.children?.count == 1 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value) + print(node.value, terminator:" ") } else if node.children?.count == 0 { - print(node.value) + print(node.value, terminator:" ") } else { print("Not a binary tree!") } @@ -58,7 +58,7 @@ func dfsStack(node: Node) { while stack.count > 0 { temp = stack.popLast()! - print(temp.value) + print(temp.value, terminator:" ") for child in temp.children! { stack.append(child) @@ -72,7 +72,7 @@ func bfsQueue(node: Node) { while queue.count > 0 { temp = queue.remove(at: 0) - print(temp.value) + print(temp.value, terminator:" ") for child in temp.children! { queue.append(child) @@ -81,24 +81,29 @@ func bfsQueue(node: Node) { } func main() { - let root = createTree(numRows: 3, numChildren: 3) + let root = createTree(numRows: 2, numChildren: 3) - print("Using recursive DFS:") + print("[#] Recursive DFS:") dfsRecursive(node: root) + print() - print("Using recursive postorder DFS:") + print("[#] Recursive Postorder DFS:") dfsRecursivePostOrder(node: root) + print() - print("Using stack-based DFS:") + print("[#] Stack-based DFS:") dfsStack(node: root) + print() - print("Using queue-based BFS:") + print("[#] Queue-based BFS:") bfsQueue(node: root) + print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("Using In-order DFS:") + print("[#] Recursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) + print() } main() From 44fe70177c7f24d90785f0862c37c6f45a1e082a Mon Sep 17 00:00:00 2001 From: Sammy Plat Date: Sat, 4 Sep 2021 20:57:49 +0200 Subject: [PATCH 78/90] removed outdated comments in Coconut implementation --- contents/tree_traversal/code/coconut/tree_traversal.coco | 5 ----- 1 file changed, 5 deletions(-) diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index ad7be7932..228d4aab7 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -61,22 +61,18 @@ if __name__ =='__main__': # A ternary tree for testing tree = create_tree(2, 3) - # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Recursive DFS:") dfs_recursive(tree) print() - # Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 print("[#] Recursive Postorder DFS:") dfs_recursive_postorder(tree) print() - # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 print("[#] Stack-based DFS:") dfs_stack(tree) print() - # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 print("[#] Queue-based BFS:") bfs_queue(tree) print() @@ -84,7 +80,6 @@ if __name__ =='__main__': # And a binary tree for testing binary_tree = create_tree(3, 2) - # Should print: 1 2 1 3 1 2 1 print("[#] Recursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From b28b2853e17054f42d457d226cc50531fc326372 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=A9r=C3=A9mie=20Gillet?= Date: Mon, 6 Sep 2021 10:10:32 +0900 Subject: [PATCH 79/90] standardize haskell output --- .../code/haskell/TreeTraversal.hs | 47 +++++++++---------- contents/tree_traversal/tree_traversal.md | 10 ++-- 2 files changed, 27 insertions(+), 30 deletions(-) diff --git a/contents/tree_traversal/code/haskell/TreeTraversal.hs b/contents/tree_traversal/code/haskell/TreeTraversal.hs index 389dc0900..e851f1833 100644 --- a/contents/tree_traversal/code/haskell/TreeTraversal.hs +++ b/contents/tree_traversal/code/haskell/TreeTraversal.hs @@ -1,7 +1,8 @@ data Tree a = Node - { node :: a - , forest :: [Tree a] - } deriving (Show) + { node :: a, + forest :: [Tree a] + } + deriving (Show) dfs :: Tree a -> [a] dfs (Node x ts) = x : concatMap dfs ts @@ -19,7 +20,7 @@ dfsStack :: Tree a -> [a] dfsStack t = go [t] where go [] = [] - go ((Node x ts):stack) = x : go (ts ++ stack) + go ((Node x ts) : stack) = x : go (ts ++ stack) bfs :: Tree a -> [a] bfs (Node x ts) = x : go ts @@ -27,26 +28,22 @@ bfs (Node x ts) = x : go ts go [] = [] go ts = map node ts ++ go (concatMap forest ts) -toBin :: Tree a -> Tree a -toBin (Node x ts) = Node x (map toBin $ take 2 ts) +createTree :: Int -> Int -> Tree Int +createTree 0 _ = Node 0 [] +createTree numRow numChild = Node numRow children + where + children = map (createTree (numRow - 1)) $ replicate numChild numChild main = do - print $ dfs testTree - print $ dfsPostOrder testTree - print $ dfsInOrder $ toBin testTree - print $ dfsStack testTree - print $ bfs testTree - -testTree :: Tree Int -testTree = - Node - 1 - [ Node 2 [Node 3 [], Node 4 [Node 5 []]] - , Node - 6 - [ Node 7 [] - , Node 8 [Node 9 [Node 10 [Node 11 []], Node 12 []]] - , Node 13 [Node 14 []] - ] - , Node 15 [] - ] + let testTree = createTree 2 3 + showNodes = unwords . map show + putStrLn "[#] Recursive DFS:" + putStrLn $ showNodes $ dfs testTree + putStrLn "[#] Recursive Postorder DFS:" + putStrLn $ showNodes $ dfsPostOrder testTree + putStrLn "[#] Stack-based DFS:" + putStrLn $ showNodes $ dfsStack testTree + putStrLn "[#] Queue-based BFS:" + putStrLn $ showNodes $ bfs testTree + putStrLn "[#] Recursive Inorder DFS for Binary Tree:" + putStrLn $ showNodes $ dfsInOrder $ createTree 3 2 diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index 6d6504760..fc493496a 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -72,7 +72,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="rs" %} [import:9-15 lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:6-7, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:7-8, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:24-30, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -128,7 +128,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="rs" %} [import:17-24, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:9-10, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:10-11, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:32-38, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -179,7 +179,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="rs" %} [import:25-40, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:12-16, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:13-17, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:40-53, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -239,7 +239,7 @@ In code, it looks like this: {% sample lang="rs" %} [import:41-48, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:18-22, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:19-23, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:55-67, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} @@ -292,7 +292,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="rs" %} [import:50-58, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:24-28, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:25-29, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:69-81, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} From 64a81297c6f5870af48368e2cad87841ca927229 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Mon, 6 Sep 2021 22:12:17 +0530 Subject: [PATCH 80/90] standardize crystal output --- .../code/crystal/tree-traversal.cr | 50 +++++-------------- 1 file changed, 12 insertions(+), 38 deletions(-) diff --git a/contents/tree_traversal/code/crystal/tree-traversal.cr b/contents/tree_traversal/code/crystal/tree-traversal.cr index e3556d8eb..dcd92773b 100644 --- a/contents/tree_traversal/code/crystal/tree-traversal.cr +++ b/contents/tree_traversal/code/crystal/tree-traversal.cr @@ -5,26 +5,26 @@ class Node end def dfs_recursive(node) - print node.id + print "#{node.id} " node.children.each{ |child| dfs_recursive child } end def dfs_recursive_postorder(node) node.children.each{ |child| dfs_recursive_postorder child } - print node.id + print "#{node.id} " end def dfs_recursive_inorder_btree(node) case node.children.size when 2 dfs_recursive_inorder_btree node.children[0] - print node.id + print "#{node.id} " dfs_recursive_inorder_btree node.children[1] when 1 dfs_recursive_inorder_btree node.children[0] - print node.id + print "#{node.id} " when 0 - print node.id + print "#{node.id} " else print "Not a binary tree!" end @@ -35,7 +35,7 @@ def dfs_stack(node) until stack.empty? temp = stack.pop - print temp.id + print "#{temp.id} " temp.children.each{ |child| stack.push child } end end @@ -45,7 +45,7 @@ def bfs_queue(node) until queue.empty? temp = queue.shift - print temp.id + print "#{temp.id} " temp.children.each{ |child| queue.push child } end end @@ -60,54 +60,28 @@ def create_tree(levels, num_childs) Node.new(levels, children) end -def print_tree(node, depth = [] of String) - puts "(#{node.id})" - depth.push " " - len = node.children.size - 1 - - (0 .. len).each do |i| - depth.each{|c| print c} - unless i == len - print "├" - depth.push "│" - print_tree node.children[i], depth - depth.pop - else - print "└" - depth.push " " - print_tree node.children[i], depth - depth.pop - end - end - depth.pop -end - def main - puts "Creating Tree" root = create_tree levels: 2, num_childs: 3 - print_tree root - puts "Using recursive DFS:" + puts "[#] Recursive DFS:" dfs_recursive root puts - puts "Using recursive DFS with post-order traversal:" + puts "[#] Recursive Postorder DFS:" dfs_recursive_postorder root puts - puts "Using stack-based DFS:" + puts "[#] Stack-based DFS:" dfs_stack root puts - puts "Using queue-based BFS:" + puts "[#] Queue-based BFS:" bfs_queue root puts - puts "Creating binary tree to test in-order traversal" root_bin = create_tree levels: 3, num_childs: 2 - print_tree root_bin - puts "Using In-order DFS:" + puts "[#] Recursive Inorder DFS for Binary Tree:" dfs_recursive_inorder_btree root_bin puts end From 1234b836e95f0e30f996fb8ce9c7af3d0e151464 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Wed, 8 Sep 2021 23:30:48 +0530 Subject: [PATCH 81/90] standardize csharp output --- .../tree_traversal/code/csharp/Program.cs | 26 +++++++++++-------- contents/tree_traversal/code/csharp/Tree.cs | 18 ++++++------- .../tree_traversal/code/csharp/code.csproj | 9 +++++++ 3 files changed, 33 insertions(+), 20 deletions(-) create mode 100644 contents/tree_traversal/code/csharp/code.csproj diff --git a/contents/tree_traversal/code/csharp/Program.cs b/contents/tree_traversal/code/csharp/Program.cs index aa2df0485..646375c51 100644 --- a/contents/tree_traversal/code/csharp/Program.cs +++ b/contents/tree_traversal/code/csharp/Program.cs @@ -7,23 +7,27 @@ class Program { static void Main(string[] args) { - Console.WriteLine("TreeTraversal"); - var tree = new Tree(3, 3); - Console.WriteLine("DFSRecursive:"); + var tree = new Tree(2, 3); + Console.WriteLine("[#] Recursive DFS:"); tree.DFSRecursive(); - Console.WriteLine("DFSStack:"); + Console.WriteLine(); + + Console.WriteLine("[#] Recursive Postorder DFS:"); + tree.DFSRecursivePostorder(); + Console.WriteLine(); + + Console.WriteLine("[#] Stack-based DFS:"); tree.DFSStack(); - Console.WriteLine("BFSQueue:"); + Console.WriteLine(); + + Console.WriteLine("[#] Queue-based BFS:"); tree.BFSQueue(); - Console.WriteLine("DFSRecursivePostorder"); - tree.DFSRecursivePostorder(); + Console.WriteLine(); - // Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work. - // Console.WriteLine("DFSRecursiveInorder (fail)"); - // tree.DFSRecursiveInorderBinary(); tree = new Tree(3, 2); - Console.WriteLine("DFSRecursiveInorder (succeed)"); + Console.WriteLine("[#] Recursive Inorder DFS for Binary Tree:"); tree.DFSRecursiveInorderBinary(); + Console.WriteLine(); } } } diff --git a/contents/tree_traversal/code/csharp/Tree.cs b/contents/tree_traversal/code/csharp/Tree.cs index e38be26fc..f581008d7 100644 --- a/contents/tree_traversal/code/csharp/Tree.cs +++ b/contents/tree_traversal/code/csharp/Tree.cs @@ -11,12 +11,12 @@ public class Tree public Tree(int depthCount, int childrenCount) { - this.Id = 1; + this.Id = depthCount; - if (!(depthCount <= 1)) + if (depthCount > 0) { for (int i = 0; i < childrenCount; i++) - this._children.Add(new Tree(this.Id * 10 + i + 1, depthCount - 1, childrenCount)); + this._children.Add(new Tree(depthCount - 1, childrenCount)); } } @@ -37,7 +37,7 @@ public void DFSRecursive() void DFSRecursive(Tree tree) { - Console.WriteLine(tree.Id); + Console.Write(tree.Id + " "); foreach (var c in tree._children) DFSRecursive(c); @@ -53,7 +53,7 @@ void DFSRecursivePostorder(Tree tree) foreach (var c in tree._children) DFSRecursivePostorder(c); - Console.WriteLine(tree.Id); + Console.Write(tree.Id + " "); } } @@ -70,11 +70,11 @@ void DFSRecursiveInorderBinary(Tree tree) if (tree._children.Count > 0) { DFSRecursiveInorderBinary(tree._children[0]); - Console.WriteLine(tree.Id); + Console.Write(tree.Id + " "); DFSRecursiveInorderBinary(tree._children[1]); } else - Console.WriteLine(tree.Id); + Console.Write(tree.Id + " "); } } @@ -85,7 +85,7 @@ public void DFSStack() while (stack.Count != 0) { - Console.WriteLine(stack.Peek().Id); + Console.Write(stack.Peek().Id + " "); var temp = stack.Pop(); foreach (var c in temp._children) @@ -100,7 +100,7 @@ public void BFSQueue() while (queue.Count != 0) { - Console.WriteLine(queue.Peek().Id); + Console.Write(queue.Peek().Id + " "); var temp = queue.Dequeue(); foreach (var c in temp._children) diff --git a/contents/tree_traversal/code/csharp/code.csproj b/contents/tree_traversal/code/csharp/code.csproj new file mode 100644 index 000000000..98c5e6713 --- /dev/null +++ b/contents/tree_traversal/code/csharp/code.csproj @@ -0,0 +1,9 @@ + + + + Exe + net5.0 + false + + + From 552e45dd876d077c3ff0ca90a78cf5d51b27f1c7 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 00:03:38 +0530 Subject: [PATCH 82/90] standardize java output Resolved the conflict with fixing dfs --- .../tree_traversal/code/java/MainClass.java | 34 +++++++++++++++++++ contents/tree_traversal/code/java/Tree.java | 26 +++++++------- 2 files changed, 47 insertions(+), 13 deletions(-) create mode 100644 contents/tree_traversal/code/java/MainClass.java diff --git a/contents/tree_traversal/code/java/MainClass.java b/contents/tree_traversal/code/java/MainClass.java new file mode 100644 index 000000000..470c58e89 --- /dev/null +++ b/contents/tree_traversal/code/java/MainClass.java @@ -0,0 +1,34 @@ +//submitted by xam4lor +public class MainClass { + public static void main(String[] args) { + Tree tree = new Tree(2, 3); + + System.out.println("[#] Recursive DFS:"); + tree.dfsRecursive(); + System.out.println(); + + System.out.println("[#] Recursive Postorder DFS:"); + tree.dfsRecursivePostOrder(); + System.out.println(); + + + System.out.println("[#] Stack-based DFS:"); + tree.dfsStack(); + System.out.println(); + + + System.out.println("[#] Queue-based BFS:"); + tree.bfsQueue(); + System.out.println(); + + + // Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work. + //System.out.println("Using in-order binary recursive DFS : (fail)"); + //tree.dfsRecursiveInOrderBinary(); + + tree = new Tree(3, 2); + System.out.println("[#] Recursive Inorder DFS for Binary Tree:"); + tree.dfsRecursiveInOrderBinary(); + System.out.println(); + } +} diff --git a/contents/tree_traversal/code/java/Tree.java b/contents/tree_traversal/code/java/Tree.java index b5c3d6542..75b4f0b5e 100644 --- a/contents/tree_traversal/code/java/Tree.java +++ b/contents/tree_traversal/code/java/Tree.java @@ -1,5 +1,5 @@ import java.util.ArrayList; -import java.util.PriorityQueue; +import java.util.LinkedList; import java.util.Queue; import java.util.Stack; @@ -8,8 +8,8 @@ public class Tree { public Tree(int rowCount, int childrenCount) { // this.root is the root node of the Tree - this.root = new Node(1); - this.createAllChildren(this.root, rowCount, childrenCount); + this.root = new Node(rowCount); + this.createAllChildren(this.root, rowCount-1, childrenCount); } @@ -18,7 +18,7 @@ public void dfsRecursive() { } private void dfsRecursive(Node node) { - System.out.println(node.id); + System.out.print(node.id + " "); for (Node n : node.children) { dfsRecursive(n); @@ -36,7 +36,7 @@ private void dfsRecursivePostOrder(Node node) { } // Here we are doing something ... - System.out.println(node.id); + System.out.print(node.id + " "); } @@ -48,15 +48,15 @@ private void dfsRecursiveInOrderBinary(Node node) { switch (node.children.size()) { case 2: dfsRecursiveInOrderBinary(node.children.get(0)); - System.out.println(node.id); + System.out.print(node.id + " "); dfsRecursiveInOrderBinary(node.children.get(1)); break; case 1: dfsRecursiveInOrderBinary(node.children.get(0)); - System.out.println(node.id); + System.out.print(node.id + " "); break; case 0: - System.out.println(node.id); + System.out.print(node.id + " "); break; default: System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!"); @@ -71,7 +71,7 @@ public void dfsStack() { Node tmp; while (stack.size() != 0) { - System.out.println(stack.peek().id); + System.out.print(stack.peek().id + " "); tmp = stack.pop(); for (Node c : tmp.children) { @@ -81,11 +81,11 @@ public void dfsStack() { } public void bfsQueue() { - Queue queue = new PriorityQueue(); + Queue queue = new LinkedList(); queue.add(this.root); while (queue.size() != 0) { - System.out.println(queue.peek().id); + System.out.print(queue.peek().id + " "); Node temp = queue.poll(); // return null if the queue is empty if (temp != null) { @@ -98,12 +98,12 @@ public void bfsQueue() { private void createAllChildren(Node node, int rowCount, int childrenCount) { - if (rowCount <= 1) { + if (rowCount < 0) { return; } for (int i = 0; i < childrenCount; i++) { - node.children.add(new Node(node.id * 10 + i + 1)); + node.children.add(new Node(rowCount)); createAllChildren(node.children.get(i), rowCount - 1, childrenCount); } } From 8c75161ae8f141f05afcb5e0493a5555818153db Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 00:12:01 +0530 Subject: [PATCH 83/90] fix php line numbers and python filename --- contents/tree_traversal/tree_traversal.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index fc493496a..9a83f7ee8 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -17,7 +17,7 @@ Trees are naturally recursive data structures, and because of this, we cannot ac [import:1-10, lang:"javascript"](code/javascript/tree.js) As a note, a `node` struct is not necessary in javascript, so this is an example of how a tree might be constructed. {% sample lang="py" %} -[import:1-4, lang:"python"](code/python/Tree_example.py) +[import:1-4, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -76,7 +76,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="swift" %} [import:24-30, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:41-49, lang:"php"](code/php/tree_traversal.php) +[import:41-47, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:7-10, lang:"crystal"](code/crystal/tree-traversal.cr) {% sample lang="st" %} @@ -132,7 +132,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="swift" %} [import:32-38, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:51-57, lang:"php"](code/php/tree_traversal.php) +[import:49-55, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:12-15, lang:"crystal"](code/crystal/tree-traversal.cr) {% sample lang="st" %} @@ -183,7 +183,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="swift" %} [import:40-53, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:59-78, lang:"php"](code/php/tree_traversal.php) +[import:57-76, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:17-31, lang:"crystal"](code/crystal/tree-traversal.cr) {% sample lang="st" %} @@ -243,7 +243,7 @@ In code, it looks like this: {% sample lang="swift" %} [import:55-67, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:80-91, lang:"php"](code/php/tree_traversal.php) +[import:78-89, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:33-41, lang:"crystal"](code/crystal/tree-traversal.cr) {% sample lang="st" %} @@ -296,7 +296,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="swift" %} [import:69-81, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:93-104, lang:"php"](code/php/tree_traversal.php) +[import:91-102, lang:"php"](code/php/tree_traversal.php) {% sample lang="crystal" %} [import:43-51, lang:"crystal"](code/crystal/tree-traversal.cr) {% sample lang="st" %} From 2fa6a38f7c6ae9f67b7e7bf50298d9fde61c79a2 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 00:30:39 +0530 Subject: [PATCH 84/90] fix coconut and python line numbers --- contents/tree_traversal/tree_traversal.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index 9a83f7ee8..94b9086a8 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -64,7 +64,7 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="js" %} [import:12-19, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:18-23, lang:"python"](code/python/Tree_example.py) +[import:17-22, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -120,7 +120,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="js" %} [import:21-28, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:26-31, lang:"python"](code/python/Tree_example.py) +[import:25-30, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -148,7 +148,7 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="m" %} [import:47-62, lang:"matlab"](code/matlab/tree.m) {% sample lang="coco" %} -[import:11-15, lang:="coconut"](codo/coconut/tree_traversal.coco) +[import:11-15, lang:="coconut"](code/coconut/tree_traversal.coco) {% endmethod %}

@@ -171,7 +171,7 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="js" %} [import:30-51, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:34-46, lang:"python"](code/python/Tree_example.py) +[import:34-45, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -231,7 +231,7 @@ In code, it looks like this: {% sample lang="js" %} [import:53-60, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:49-60, lang:"python"](code/python/Tree_example.py) +[import:48-59, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -284,7 +284,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="js" %} [import:62-69, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:63-75, lang:"python"](code/python/Tree_example.py) +[import:62-72, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %}

@@ -345,7 +345,7 @@ Here is a video describing tree traversal: {% sample lang="js" %} [import, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import, lang:"python"](code/python/Tree_example.py) +[import, lang:"python"](code/python/tree_traversal.py) {% sample lang="scratch" %} The code snippets were taken from this [Scratch project](https://scratch.mit.edu/projects/174017753/) From b9ebcd2af26e5b90e4b748ff09c78ef75500c8fa Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 00:50:00 +0530 Subject: [PATCH 85/90] fix minor bug in C --- contents/tree_traversal/code/c/tree_traversal.c | 1 + 1 file changed, 1 insertion(+) diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index 3c1db527b..bc01ed609 100644 --- a/contents/tree_traversal/code/c/tree_traversal.c +++ b/contents/tree_traversal/code/c/tree_traversal.c @@ -140,3 +140,4 @@ int main() { destroy_tree(root_binary); return 0; +} From dd95d0d439a09368b19f3e93c7c41cf0a6d207bd Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 01:01:38 +0530 Subject: [PATCH 86/90] fix labels and minor bug in go --- contents/tree_traversal/code/golang/treetraversal.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index deba1347d..ac18ce262 100644 --- a/contents/tree_traversal/code/golang/treetraversal.go +++ b/contents/tree_traversal/code/golang/treetraversal.go @@ -16,7 +16,7 @@ func dfsRecursive(n *node) { func dfsRecursivePostorder(n *node) { for _, child := range n.children { - dfsRecursive(child) + dfsRecursivePostorder(child) } fmt.Printf("%d ", n.id) } @@ -77,11 +77,11 @@ func main() { root := createTree(2, 3) binTree := createTree(3, 2) - fmt.Println("[#] DFS Recursive:") + fmt.Println("[#] Recursive DFS:") dfsRecursive(root) fmt.Println() - fmt.Println("[#] DFS Postorder Recursive:") + fmt.Println("[#] Recursive Postorder DFS:") dfsRecursivePostorder(root) fmt.Println() @@ -93,7 +93,7 @@ func main() { bfsQueue(root) fmt.Println() - fmt.Println("[#] DFS Inorder for Binary Tree:") + fmt.Println("[#] Recursive Inorder DFS for Binary Tree:") dfsRecursiveInorderBtree(binTree) fmt.Println() From f71124a2853782287e9e6697124d8ca6ca5ae358 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 9 Sep 2021 01:05:27 +0530 Subject: [PATCH 87/90] minor label fix in python --- contents/tree_traversal/code/python/tree_traversal.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py index 98dad806d..341f949f1 100644 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -84,7 +84,7 @@ def main(): dfs_recursive_postorder(tree) print() - print("[#] Stack-based DFS :") + print("[#] Stack-based DFS:") dfs_stack(tree) print() @@ -94,7 +94,7 @@ def main(): binary_tree = create_tree(Node(), 3, 2) - print("[#] Recursive Inorder Binary Tree:") + print("[#] Recursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() From 1b83e14de4ef529fbfc276aaf41e299405a62406 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Thu, 21 Oct 2021 11:39:24 +0530 Subject: [PATCH 88/90] use [#]\n for readability --- contents/tree_traversal/code/c++/tree_example.cpp | 10 +++++----- contents/tree_traversal/code/c/tree_traversal.c | 10 +++++----- contents/tree_traversal/code/clisp/tree-traversal.lisp | 10 +++++----- .../tree_traversal/code/coconut/tree_traversal.coco | 10 +++++----- contents/tree_traversal/code/crystal/tree-traversal.cr | 10 +++++----- contents/tree_traversal/code/csharp/Program.cs | 10 +++++----- contents/tree_traversal/code/golang/treetraversal.go | 10 +++++----- contents/tree_traversal/code/haskell/TreeTraversal.hs | 10 +++++----- contents/tree_traversal/code/java/MainClass.java | 10 +++++----- contents/tree_traversal/code/javascript/tree.js | 10 +++++----- contents/tree_traversal/code/julia/Tree.jl | 10 +++++----- contents/tree_traversal/code/php/tree_traversal.php | 10 +++++----- contents/tree_traversal/code/python/tree_traversal.py | 10 +++++----- contents/tree_traversal/code/rust/tree.rs | 10 +++++----- contents/tree_traversal/code/swift/tree.swift | 10 +++++----- 15 files changed, 75 insertions(+), 75 deletions(-) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index d109f11e5..71a84c686 100644 --- a/contents/tree_traversal/code/c++/tree_example.cpp +++ b/contents/tree_traversal/code/c++/tree_example.cpp @@ -102,19 +102,19 @@ int main() { // Creating Tree in main auto root = create_tree(2, 3); auto binary_root = create_tree(3, 2); - std::cout << "[#] Recursive DFS:\n"; + std::cout << "[#]\nRecursive DFS:\n"; dfs_recursive(root); std::cout << '\n'; - std::cout << "[#] Recursive Postorder DFS:\n"; + std::cout << "[#]\nRecursive Postorder DFS:\n"; dfs_recursive_postorder(root); std::cout << '\n'; - std::cout << "[#] Stack-based DFS:\n"; + std::cout << "[#]\nStack-based DFS:\n"; dfs_stack(root); std::cout << '\n'; - std::cout << "[#] Queue-based BFS:\n"; + std::cout << "[#]\nQueue-based BFS:\n"; bfs_queue(root); std::cout << '\n'; - std::cout << "[#] Recursive Inorder DFS for Binary Tree:\n"; + std::cout << "[#]\nRecursive Inorder DFS for Binary Tree:\n"; dfs_recursive_inorder_btree(binary_root); std::cout << '\n'; diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index bc01ed609..16be536c8 100644 --- a/contents/tree_traversal/code/c/tree_traversal.c +++ b/contents/tree_traversal/code/c/tree_traversal.c @@ -115,26 +115,26 @@ void bfs_queue(struct node n) { int main() { struct node root = create_tree(2, 3); - printf("[#] Recursive DFS:\n"); + printf("[#]\nRecursive DFS:\n"); dfs_recursive(root); printf("\n"); - printf("[#] Recursive Postorder DFS:\n"); + printf("[#]\nRecursive Postorder DFS:\n"); dfs_recursive_postorder(root); printf("\n"); - printf("[#] Stack-based DFS:\n"); + printf("[#]\nStack-based DFS:\n"); dfs_stack(root); printf("\n"); - printf("[#] Queue-based BFS:\n"); + printf("[#]\nQueue-based BFS:\n"); bfs_queue(root); printf("\n"); destroy_tree(root); struct node root_binary = create_tree(3, 2); - printf("[#] Recursive Inorder DFS for Binary Tree:\n"); + printf("[#]\nRecursive Inorder DFS for Binary Tree:\n"); dfs_recursive_inorder_btree(root_binary); printf("\n"); diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 31395f3ac..8c74db43b 100644 --- a/contents/tree_traversal/code/clisp/tree-traversal.lisp +++ b/contents/tree_traversal/code/clisp/tree-traversal.lisp @@ -73,26 +73,26 @@ (defvar binary-tree (make-tree 3 2)) ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 -(format t "[#] Recursive DFS:~%") +(format t "[#]~%Recursive DFS:~%") (dfs-recursive tree) (format t "~%") ;; Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 -(format t "[#] Recursive Postorder DFS:~%") +(format t "[#]~%Recursive Postorder DFS:~%") (dfs-recursive-postorder tree) (format t "~%") ;; Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 -(format t "[#] Stack-based DFS:~%") +(format t "[#]~%Stack-based DFS:~%") (dfs-stack tree) (format t "~%") ;; Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 -(format t "[#] Queue-based BFS:~%") +(format t "[#]~%Queue-based BFS:~%") (bfs-queue tree) (format t "~%") ;; Should print: 1 2 1 3 1 2 1 -(format t "[#] Recursive Inorder DFS for Binary Tree:~%") +(format t "[#]~%Recursive Inorder DFS for Binary Tree:~%") (dfs-recursive-inorder-btree binary-tree) (format t "~%") diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index 228d4aab7..776708f6e 100644 --- a/contents/tree_traversal/code/coconut/tree_traversal.coco +++ b/contents/tree_traversal/code/coconut/tree_traversal.coco @@ -61,26 +61,26 @@ if __name__ =='__main__': # A ternary tree for testing tree = create_tree(2, 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfs_recursive(tree) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfs_recursive_postorder(tree) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfs_stack(tree) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfs_queue(tree) print() # And a binary tree for testing binary_tree = create_tree(3, 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() diff --git a/contents/tree_traversal/code/crystal/tree-traversal.cr b/contents/tree_traversal/code/crystal/tree-traversal.cr index dcd92773b..e63dbbb7e 100644 --- a/contents/tree_traversal/code/crystal/tree-traversal.cr +++ b/contents/tree_traversal/code/crystal/tree-traversal.cr @@ -63,25 +63,25 @@ end def main root = create_tree levels: 2, num_childs: 3 - puts "[#] Recursive DFS:" + puts "[#]\nRecursive DFS:" dfs_recursive root puts - puts "[#] Recursive Postorder DFS:" + puts "[#]\nRecursive Postorder DFS:" dfs_recursive_postorder root puts - puts "[#] Stack-based DFS:" + puts "[#]\nStack-based DFS:" dfs_stack root puts - puts "[#] Queue-based BFS:" + puts "[#]\nQueue-based BFS:" bfs_queue root puts root_bin = create_tree levels: 3, num_childs: 2 - puts "[#] Recursive Inorder DFS for Binary Tree:" + puts "[#]\nRecursive Inorder DFS for Binary Tree:" dfs_recursive_inorder_btree root_bin puts end diff --git a/contents/tree_traversal/code/csharp/Program.cs b/contents/tree_traversal/code/csharp/Program.cs index 646375c51..4308794dd 100644 --- a/contents/tree_traversal/code/csharp/Program.cs +++ b/contents/tree_traversal/code/csharp/Program.cs @@ -8,24 +8,24 @@ class Program static void Main(string[] args) { var tree = new Tree(2, 3); - Console.WriteLine("[#] Recursive DFS:"); + Console.WriteLine("[#]\nRecursive DFS:"); tree.DFSRecursive(); Console.WriteLine(); - Console.WriteLine("[#] Recursive Postorder DFS:"); + Console.WriteLine("[#]\nRecursive Postorder DFS:"); tree.DFSRecursivePostorder(); Console.WriteLine(); - Console.WriteLine("[#] Stack-based DFS:"); + Console.WriteLine("[#]\nStack-based DFS:"); tree.DFSStack(); Console.WriteLine(); - Console.WriteLine("[#] Queue-based BFS:"); + Console.WriteLine("[#]\nQueue-based BFS:"); tree.BFSQueue(); Console.WriteLine(); tree = new Tree(3, 2); - Console.WriteLine("[#] Recursive Inorder DFS for Binary Tree:"); + Console.WriteLine("[#]\nRecursive Inorder DFS for Binary Tree:"); tree.DFSRecursiveInorderBinary(); Console.WriteLine(); } diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index ac18ce262..fb5142712 100644 --- a/contents/tree_traversal/code/golang/treetraversal.go +++ b/contents/tree_traversal/code/golang/treetraversal.go @@ -77,23 +77,23 @@ func main() { root := createTree(2, 3) binTree := createTree(3, 2) - fmt.Println("[#] Recursive DFS:") + fmt.Println("[#]\nRecursive DFS:") dfsRecursive(root) fmt.Println() - fmt.Println("[#] Recursive Postorder DFS:") + fmt.Println("[#]\nRecursive Postorder DFS:") dfsRecursivePostorder(root) fmt.Println() - fmt.Println("[#] Stack-based DFS:") + fmt.Println("[#]\nStack-based DFS:") dfsStack(root) fmt.Println() - fmt.Println("[#] Queue-based BFS:") + fmt.Println("[#]\nQueue-based BFS:") bfsQueue(root) fmt.Println() - fmt.Println("[#] Recursive Inorder DFS for Binary Tree:") + fmt.Println("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInorderBtree(binTree) fmt.Println() diff --git a/contents/tree_traversal/code/haskell/TreeTraversal.hs b/contents/tree_traversal/code/haskell/TreeTraversal.hs index e851f1833..1f9d27db8 100644 --- a/contents/tree_traversal/code/haskell/TreeTraversal.hs +++ b/contents/tree_traversal/code/haskell/TreeTraversal.hs @@ -37,13 +37,13 @@ createTree numRow numChild = Node numRow children main = do let testTree = createTree 2 3 showNodes = unwords . map show - putStrLn "[#] Recursive DFS:" + putStrLn "[#]\nRecursive DFS:" putStrLn $ showNodes $ dfs testTree - putStrLn "[#] Recursive Postorder DFS:" + putStrLn "[#]\nRecursive Postorder DFS:" putStrLn $ showNodes $ dfsPostOrder testTree - putStrLn "[#] Stack-based DFS:" + putStrLn "[#]\nStack-based DFS:" putStrLn $ showNodes $ dfsStack testTree - putStrLn "[#] Queue-based BFS:" + putStrLn "[#]\nQueue-based BFS:" putStrLn $ showNodes $ bfs testTree - putStrLn "[#] Recursive Inorder DFS for Binary Tree:" + putStrLn "[#]\nRecursive Inorder DFS for Binary Tree:" putStrLn $ showNodes $ dfsInOrder $ createTree 3 2 diff --git a/contents/tree_traversal/code/java/MainClass.java b/contents/tree_traversal/code/java/MainClass.java index 470c58e89..d7c062c03 100644 --- a/contents/tree_traversal/code/java/MainClass.java +++ b/contents/tree_traversal/code/java/MainClass.java @@ -3,21 +3,21 @@ public class MainClass { public static void main(String[] args) { Tree tree = new Tree(2, 3); - System.out.println("[#] Recursive DFS:"); + System.out.println("[#]\nRecursive DFS:"); tree.dfsRecursive(); System.out.println(); - System.out.println("[#] Recursive Postorder DFS:"); + System.out.println("[#]\nRecursive Postorder DFS:"); tree.dfsRecursivePostOrder(); System.out.println(); - System.out.println("[#] Stack-based DFS:"); + System.out.println("[#]\nStack-based DFS:"); tree.dfsStack(); System.out.println(); - System.out.println("[#] Queue-based BFS:"); + System.out.println("[#]\nQueue-based BFS:"); tree.bfsQueue(); System.out.println(); @@ -27,7 +27,7 @@ public static void main(String[] args) { //tree.dfsRecursiveInOrderBinary(); tree = new Tree(3, 2); - System.out.println("[#] Recursive Inorder DFS for Binary Tree:"); + System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:"); tree.dfsRecursiveInOrderBinary(); System.out.println(); } diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index 13c4ff7a6..1fbffa02a 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -69,20 +69,20 @@ function bfs(tree) { } const root = createTree(2, 3); -console.log("[#] Recursive DFS:"); +console.log("[#]\nRecursive DFS:"); dfsPreorder(root); console.log(); -console.log("[#] Recursive Postorder DFS:"); +console.log("[#]\nRecursive Postorder DFS:"); dfsPostorder(root); console.log(); -console.log("[#] Stack-based DFS:"); +console.log("[#]\nStack-based DFS:"); dfsIterative(root); console.log(); -console.log("[#] Queue-based BFS:"); +console.log("[#]\nQueue-based BFS:"); bfs(root); console.log(); const root_binary = createTree(3, 2); -console.log("[#] Recursive Inorder DFS for Binary Tree:"); +console.log("[#]\nRecursive Inorder DFS for Binary Tree:"); dfsInorder(root_binary); console.log(); diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index 652048c71..abc207074 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -86,24 +86,24 @@ end function main() root = create_tree(2, 3) - println("[#] Recursive DFS:") + println("[#]\nRecursive DFS:") DFS_recursive(root); println() - println("[#] Recursive Postorder DFS:") + println("[#]\nRecursive Postorder DFS:") DFS_recursive_postorder(root); println() - println("[#] Stack-based DFS:") + println("[#]\nStack-based DFS:") DFS_stack(root); println() - println("[#] Queue-based BFS:") + println("[#]\nQueue-based BFS:") BFS_queue(root); println() root_binary = create_tree(3,2) - println("[#] Recursive Inorder DFS for Binary Tree:") + println("[#]\nRecursive Inorder DFS for Binary Tree:") DFS_recursive_inorder_btree(root_binary) println() end diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index 0951cea79..3c829977b 100644 --- a/contents/tree_traversal/code/php/tree_traversal.php +++ b/contents/tree_traversal/code/php/tree_traversal.php @@ -118,19 +118,19 @@ function generate_tree(int $numOfRows, int $numOfChildren): Tree $node = generate_tree(2, 3); -echo '[#] Recursive DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive DFS:' . PHP_EOL; TreeTraversal::DFSRecursive($node); echo PHP_EOL; -echo '[#] Recursive Postorder DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive Postorder DFS:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); echo PHP_EOL; -echo '[#] Stack-based DFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Stack-based DFS:' . PHP_EOL; TreeTraversal::DFSStack($node); echo PHP_EOL; -echo '[#] Queue-based BFS:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Queue-based BFS:' . PHP_EOL; TreeTraversal::DFSQueue($node); echo PHP_EOL; @@ -138,6 +138,6 @@ function generate_tree(int $numOfRows, int $numOfChildren): Tree // comment out the generation of the new tree below. // If you do that, an exception will be thrown $node = generate_tree(3, 2); -echo '[#] Recursive Inorder DFS for Binary Tree:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive Inorder DFS for Binary Tree:' . PHP_EOL; TreeTraversal::DFSRecursiveInorderBinary($node); echo PHP_EOL; diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py index 341f949f1..735837bdd 100644 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -76,25 +76,25 @@ def bfs_queue(node): def main(): tree = create_tree(Node(), 2, 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfs_recursive(tree) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfs_recursive_postorder(tree) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfs_stack(tree) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfs_queue(tree) print() binary_tree = create_tree(Node(), 3, 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfs_recursive_inorder_btree(binary_tree) print() diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index 35319454a..60e833858 100644 --- a/contents/tree_traversal/code/rust/tree.rs +++ b/contents/tree_traversal/code/rust/tree.rs @@ -78,23 +78,23 @@ fn create_tree(num_row: u64, num_child: u64) -> Node { fn main() { let root = create_tree(2, 3); - println!("[#] Recursive DFS:"); + println!("[#]\nRecursive DFS:"); dfs_recursive(&root); println!(); - println!("[#] Recursive Postorder DFS:"); + println!("[#]\nRecursive Postorder DFS:"); dfs_recursive_postorder(&root); println!(); - println!("[#] Stack-based DFS:"); + println!("[#]\nStack-based DFS:"); dfs_stack(&root); println!(); - println!("[#] Queue-based BFS:"); + println!("[#]\nQueue-based BFS:"); bfs_queue(&root); println!(); - println!("[#] Recursive Inorder DFS for Binary Tree:"); + println!("[#]\nRecursive Inorder DFS for Binary Tree:"); let root_binary = create_tree(3, 2); dfs_recursive_inorder_btree(&root_binary); println!(); diff --git a/contents/tree_traversal/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index 86e561435..ae64315ec 100644 --- a/contents/tree_traversal/code/swift/tree.swift +++ b/contents/tree_traversal/code/swift/tree.swift @@ -83,25 +83,25 @@ func bfsQueue(node: Node) { func main() { let root = createTree(numRows: 2, numChildren: 3) - print("[#] Recursive DFS:") + print("[#]\nRecursive DFS:") dfsRecursive(node: root) print() - print("[#] Recursive Postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfsRecursivePostOrder(node: root) print() - print("[#] Stack-based DFS:") + print("[#]\nStack-based DFS:") dfsStack(node: root) print() - print("[#] Queue-based BFS:") + print("[#]\nQueue-based BFS:") bfsQueue(node: root) print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("[#] Recursive Inorder DFS for Binary Tree:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) print() } From 7a575b5d65224bc4f8b6fab68acbff3619344cf1 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Sun, 24 Oct 2021 02:24:59 +0530 Subject: [PATCH 89/90] julia: change printf to print --- contents/tree_traversal/code/julia/Tree.jl | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/contents/tree_traversal/code/julia/Tree.jl b/contents/tree_traversal/code/julia/Tree.jl index abc207074..7382fdad0 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -8,7 +8,7 @@ end function DFS_recursive(n::Node) # Here we are doing something... - @printf("%i ", n.ID) + print(n.ID, " ") for child in n.children DFS_recursive(child) @@ -22,7 +22,7 @@ function DFS_recursive_postorder(n::Node) end # Here we are doing something... - @printf("%i ", n.ID) + print(n.ID, " ") end # This assumes only 2 children, but accounts for other possibilities @@ -30,13 +30,13 @@ function DFS_recursive_inorder_btree(n::Node) if (length(n.children) == 2) DFS_recursive_inorder_btree(n.children[1]) - @printf("%i ", n.ID) + print(n.ID, " ") DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - @printf("%i ", n.ID) + print(n.ID, " ") elseif (length(n.children) == 0) - @printf("%i ", n.ID) + print(n.ID, " ") else println("Not a binary tree!") end @@ -47,7 +47,7 @@ function DFS_stack(n::Node) push!(s, n) while(length(s) > 0) - @printf("%i ", top(s).ID) + print(top(s).ID, " ") temp = pop!(s) for child in temp.children push!(s, child) @@ -60,7 +60,7 @@ function BFS_queue(n::Node) enqueue!(q, n) while(length(q) > 0) - @printf("%i ", first(q).ID) + print(first(q).ID, " ") temp = dequeue!(q) for child in temp.children enqueue!(q, child) From ad9943929236238fef178c6676782782c027fb78 Mon Sep 17 00:00:00 2001 From: Ishaan Verma Date: Mon, 25 Oct 2021 16:59:33 +0530 Subject: [PATCH 90/90] update Tree.java. remove MainClass.java --- contents/tree_traversal/code/java/Tree.java | 32 +++++++++++---------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/contents/tree_traversal/code/java/Tree.java b/contents/tree_traversal/code/java/Tree.java index 75b4f0b5e..93e508f6c 100644 --- a/contents/tree_traversal/code/java/Tree.java +++ b/contents/tree_traversal/code/java/Tree.java @@ -128,32 +128,34 @@ public int compareTo(Node other) { } public static void main(String[] args) { - System.out.println("Creating Tree"); - Tree tree = new Tree(3, 3); + Tree tree = new Tree(2, 3); - System.out.println("Using recursive DFS :"); + System.out.println("[#]\nRecursive DFS:"); tree.dfsRecursive(); + System.out.println(); - System.out.println("Using stack-based DFS :"); + System.out.println("[#]\nRecursive Postorder DFS:"); + tree.dfsRecursivePostOrder(); + System.out.println(); + + + System.out.println("[#]\nStack-based DFS:"); tree.dfsStack(); + System.out.println(); - System.out.println("Using queue-based BFS :"); - tree.bfsQueue(); - System.out.println("Using post-order recursive DFS :"); - tree.dfsRecursivePostOrder(); + System.out.println("[#]\nQueue-based BFS:"); + tree.bfsQueue(); + System.out.println(); // Uncommenting the following 2 lines will result in an exception thrown because at least one Node of the Tree has more than 2 children and therefor a DFSRecursiveInorderBinary doesn't work. - System.out.println("Using in-order binary recursive DFS : (fail)"); - tree.dfsRecursiveInOrderBinary(); + //System.out.println("Using in-order binary recursive DFS : (fail)"); + //tree.dfsRecursiveInOrderBinary(); tree = new Tree(3, 2); - System.out.println("Using in-order binary recursive DFS : (succeed)"); + System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:"); tree.dfsRecursiveInOrderBinary(); - - - System.out.println(""); + System.out.println(); } - }