From 314a0851bcd7062264ed5e849fa820621a5ef5aa Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:48:39 +0200 Subject: [PATCH 01/30] Standardize bash output --- contents/euclidean_algorithm/code/bash/euclid.bash | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/bash/euclid.bash b/contents/euclidean_algorithm/code/bash/euclid.bash index bef4b5da0..0ddd49537 100755 --- a/contents/euclidean_algorithm/code/bash/euclid.bash +++ b/contents/euclidean_algorithm/code/bash/euclid.bash @@ -38,6 +38,6 @@ euclid_sub() { } result=$(euclid_mod $((64 * 67)) $((64 * 81))) -echo "$result" +echo -e "[#]\nModulus-based euclidean algorithm result:\n$result" result=$(euclid_sub $((128 * 12)) $((128 * 77))) -echo "$result" +echo -e "[#]\nSubtraction-based euclidean algorithm result:\n$result" From abbd81aa2c42f29404ad06e72b26d08d2f8b6b9a Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:48:51 +0200 Subject: [PATCH 02/30] Standardize c output --- contents/euclidean_algorithm/code/c/euclidean_example.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/c/euclidean_example.c b/contents/euclidean_algorithm/code/c/euclidean_example.c index 16b0ce9ea..a6e4c0c02 100644 --- a/contents/euclidean_algorithm/code/c/euclidean_example.c +++ b/contents/euclidean_algorithm/code/c/euclidean_example.c @@ -33,8 +33,8 @@ int main() { int check1 = euclid_mod(64 * 67, 64 * 81); int check2 = euclid_sub(128 * 12, 128 * 77); - printf("%d\n", check1); - printf("%d\n", check2); + printf("[#]\nModulus-based euclidean algorithm result:\n%d\n", check1); + printf("[#]\nSubtraction-based euclidean algorithm result:\n%d\n", check2); return 0; } From 195fe6fcf1453d7f3e5570ccdb155a90dd9c6a9b Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:48:58 +0200 Subject: [PATCH 03/30] Standardize c++ output --- contents/euclidean_algorithm/code/c++/euclidean.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/c++/euclidean.cpp b/contents/euclidean_algorithm/code/c++/euclidean.cpp index f7b818802..1f6c04e27 100644 --- a/contents/euclidean_algorithm/code/c++/euclidean.cpp +++ b/contents/euclidean_algorithm/code/c++/euclidean.cpp @@ -34,6 +34,6 @@ int main() { auto check1 = euclid_mod(64 * 67, 64 * 81); auto check2 = euclid_sub(128 * 12, 128 * 77); - std::cout << check1 << '\n'; - std::cout << check2 << '\n'; + std::cout << "[#]\nModulus-based euclidean algorithm result:\n" << check1 << '\n'; + std::cout << "[#]\nSubtraction-based euclidean algorithm result:\n" << check2 << '\n'; } From bad949df2b5b1f16df36ced26497510e410516fe Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:04 +0200 Subject: [PATCH 04/30] Standardize lisp output --- contents/euclidean_algorithm/code/clisp/euclidean.lisp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/clisp/euclidean.lisp b/contents/euclidean_algorithm/code/clisp/euclidean.lisp index 62f525ac3..19cba7358 100644 --- a/contents/euclidean_algorithm/code/clisp/euclidean.lisp +++ b/contents/euclidean_algorithm/code/clisp/euclidean.lisp @@ -17,8 +17,10 @@ (abs a) (euclid-mod b (mod a b)))) -(print (euclid-sub (* 64 67) (* 64 81))) -(print (euclid-mod (* 128 12) (* 128 77))) +(format T "[#]~%Modulus-based euclidean algorithm result:~%") +(format T "~d~%" (euclid-sub (* 64 67) (* 64 81))) +(format T "[#]~%Subtraction-based euclidean algorithm result:~%") +(format T "~d~%" (euclid-mod (* 128 12) (* 128 77))) ;; Quick test (assert From 719cd556c9e571b617cee71a3fc428ff46afd5f1 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:11 +0200 Subject: [PATCH 05/30] Standardize c# output --- contents/euclidean_algorithm/code/csharp/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/contents/euclidean_algorithm/code/csharp/Program.cs b/contents/euclidean_algorithm/code/csharp/Program.cs index edf1edfd4..80857df27 100644 --- a/contents/euclidean_algorithm/code/csharp/Program.cs +++ b/contents/euclidean_algorithm/code/csharp/Program.cs @@ -7,12 +7,13 @@ class Program { static void Main(string[] args) { - Console.WriteLine("EuclideanAlgorithm"); var euclideanAlgorithm = new EuclideanAlgorithm(); int check = euclideanAlgorithm.EuclidMod(64 * 67, 64 * 81); int check2 = euclideanAlgorithm.EuclidSub(128 * 12, 128 * 77); + Console.WriteLine("[#]\nModulus-based euclidean algorithm result:"); Console.WriteLine(check); + Console.WriteLine("[#]\nSubtraction-based euclidean algorithm result:"); Console.WriteLine(check2); } } From 1a2f7531e3807b2461d22c136dcf846502569e90 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:20 +0200 Subject: [PATCH 06/30] Standardize d output --- contents/euclidean_algorithm/code/d/euclidean_algorithm.d | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/d/euclidean_algorithm.d b/contents/euclidean_algorithm/code/d/euclidean_algorithm.d index 042a9bae1..585d0aa1b 100644 --- a/contents/euclidean_algorithm/code/d/euclidean_algorithm.d +++ b/contents/euclidean_algorithm/code/d/euclidean_algorithm.d @@ -37,6 +37,6 @@ void main() auto check1 = euclid_mod(64 * 67, 64 * 81); auto check2 = euclid_sub(128 * 12, 128 * 77); - writeln("Modulus-based euclidean algorithm result: ", check1); - writeln("Subtraction-based euclidean algorithm result: ", check2); + writeln("[#]\nModulus-based euclidean algorithm result:\n", check1); + writeln("[#]\nSubtraction-based euclidean algorithm result:\n", check2); } From 0c640e3a7437d8d05a8ee98936a442330bf67e79 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:28 +0200 Subject: [PATCH 07/30] Standardize fortran output --- .../code/fortran/euclidean.f90 | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/contents/euclidean_algorithm/code/fortran/euclidean.f90 b/contents/euclidean_algorithm/code/fortran/euclidean.f90 index 3107e4de2..086d2fee2 100644 --- a/contents/euclidean_algorithm/code/fortran/euclidean.f90 +++ b/contents/euclidean_algorithm/code/fortran/euclidean.f90 @@ -38,12 +38,18 @@ PROGRAM euclidean IMPLICIT NONE INTEGER :: a, b, euclid_sub, euclid_mod - a = 24 - b = 27 - WRITE(*,*) 'Subtraction method: GCD is: ', euclid_sub(a, b) + a = 64 * 67 + b = 64 * 81 - a = 24 - b = 27 - WRITE(*,*) 'Modulus method: GCD is: ', euclid_mod(a, b) + WRITE(*,'(a)') '[#]' + WRITE(*,'(a)') 'Modulus-based euclidean algorithm result:' + WRITE(*, '(g0)') euclid_mod(a, b) + + a = 128 * 12 + b = 128 * 77 + + WRITE(*,'(a)') '[#]' + WRITE(*,'(a)') 'Subtraction-based euclidean algorithm result::' + WRITE(*, '(g0)') euclid_sub(a, b) END PROGRAM euclidean From f6b4c16aaf067464a62b4f64300c4094fe971c13 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:34 +0200 Subject: [PATCH 08/30] Standardize go output --- contents/euclidean_algorithm/code/go/euclidean.go | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/go/euclidean.go b/contents/euclidean_algorithm/code/go/euclidean.go index f457b1849..ea543fe75 100644 --- a/contents/euclidean_algorithm/code/go/euclidean.go +++ b/contents/euclidean_algorithm/code/go/euclidean.go @@ -41,6 +41,8 @@ func main() { check1 := euclidMod(64*67, 64*81) check2 := euclidSub(128*12, 128*77) + fmt.Println("[#]\nModulus-based euclidean algorithm result:") fmt.Println(check1) + fmt.Println("[#]\nSubtraction-based euclidean algorithm result:") fmt.Println(check2) } From e525f061173edf26472963851bcccde0f87fa0e1 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:39 +0200 Subject: [PATCH 09/30] Standardize haskell output --- .../euclidean_algorithm/code/haskell/euclidean_algorithm.hs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/haskell/euclidean_algorithm.hs b/contents/euclidean_algorithm/code/haskell/euclidean_algorithm.hs index 9227de4e9..917aef7df 100644 --- a/contents/euclidean_algorithm/code/haskell/euclidean_algorithm.hs +++ b/contents/euclidean_algorithm/code/haskell/euclidean_algorithm.hs @@ -31,5 +31,7 @@ main :: IO () main = do let chk1 = euclidMod (64 * 67) (64 * 81) chk2 = euclidSub (128 * 12) (128 * 77) + putStrLn "[#]\nModulus-based euclidean algorithm result:" print chk1 + putStrLn "[#]\nSubtraction-based euclidean algorithm result:" print chk2 From b443f666d562e15d09663affe5cde8477d35e7e6 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:44 +0200 Subject: [PATCH 10/30] Standardize java output --- contents/euclidean_algorithm/code/java/EuclideanAlgo.java | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/java/EuclideanAlgo.java b/contents/euclidean_algorithm/code/java/EuclideanAlgo.java index 95d233f58..ac53379da 100644 --- a/contents/euclidean_algorithm/code/java/EuclideanAlgo.java +++ b/contents/euclidean_algorithm/code/java/EuclideanAlgo.java @@ -26,7 +26,9 @@ public static int euclidMod(int a, int b) { } public static void main(String[] args) { + System.out.println("[#]\nModulus-based euclidean algorithm result:"); System.out.println(euclidMod(64 * 67, 64 * 81)); + System.out.println("[#]\nSubtraction-based euclidean algorithm result:"); System.out.println(euclidSub(128 * 12, 128 * 77)); } } From 27afabfba503fb1bb2f920d8e681ecb4f76cf07d Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:49:49 +0200 Subject: [PATCH 11/30] Standardize javascript output This also fixes a bug in the original implementation. --- contents/euclidean_algorithm/code/coconut/euclidean.coco | 4 ++-- .../code/javascript/euclidean_example.js | 6 ++++-- contents/euclidean_algorithm/code/julia/euclidean.jl | 4 ++-- .../euclidean_algorithm/code/python/euclidean_example.py | 4 ++-- contents/euclidean_algorithm/code/ruby/euclidean.rb | 9 ++++----- 5 files changed, 14 insertions(+), 13 deletions(-) diff --git a/contents/euclidean_algorithm/code/coconut/euclidean.coco b/contents/euclidean_algorithm/code/coconut/euclidean.coco index 8f5b5c9d7..abb649193 100644 --- a/contents/euclidean_algorithm/code/coconut/euclidean.coco +++ b/contents/euclidean_algorithm/code/coconut/euclidean.coco @@ -15,5 +15,5 @@ addpattern def euclid_mod(0, b is int) = b addpattern def euclid_mod(a is int, b is int) = euclid_mod(b, a % b) if __name__ == '__main__': - print('Euclidean mod:', euclid_mod(64 * 67, 64 * 81)) - print('Euclidean sub:', euclid_sub(128 * 12, 128 * 77)) + print('[#]\nModulus-based euclidean algorithm result:\n', euclid_mod(64 * 67, 64 * 81)) + print('[#]\nSubtraction-based euclidean algorithm result:\n', euclid_sub(128 * 12, 128 * 77)) diff --git a/contents/euclidean_algorithm/code/javascript/euclidean_example.js b/contents/euclidean_algorithm/code/javascript/euclidean_example.js index fbaf4bfcc..2199c37dc 100644 --- a/contents/euclidean_algorithm/code/javascript/euclidean_example.js +++ b/contents/euclidean_algorithm/code/javascript/euclidean_example.js @@ -18,14 +18,16 @@ function euclidSub(a, b) { while (a !== b) { if (a > b) { - a -= a - b; + a -= b; } else { - b = b - a; + b -= a; } } return a; } +console.log('[#]\nModulus-based euclidean algorithm result:') console.log(euclidMod(64 * 67, 64 * 81)); +console.log('[#]\nSubtraction-based euclidean algorithm result:') console.log(euclidSub(128 * 12, 128 * 77)); diff --git a/contents/euclidean_algorithm/code/julia/euclidean.jl b/contents/euclidean_algorithm/code/julia/euclidean.jl index 744ae2187..a85f931ae 100644 --- a/contents/euclidean_algorithm/code/julia/euclidean.jl +++ b/contents/euclidean_algorithm/code/julia/euclidean.jl @@ -28,8 +28,8 @@ function main() check1 = euclid_mod(64 * 67, 64 * 81); check2 = euclid_sub(128 * 12, 128 * 77); - println("Modulus-based euclidean algorithm result: $(check1)") - println("subtraction-based euclidean algorithm result: $(check2)") + println("[#]\nModulus-based euclidean algorithm result:\n$(check1)") + println("[#]\nSubtraction-based euclidean algorithm result:\n$(check2)") end diff --git a/contents/euclidean_algorithm/code/python/euclidean_example.py b/contents/euclidean_algorithm/code/python/euclidean_example.py index 0badc2ca8..37c9278f7 100644 --- a/contents/euclidean_algorithm/code/python/euclidean_example.py +++ b/contents/euclidean_algorithm/code/python/euclidean_example.py @@ -27,5 +27,5 @@ def euclid_sub(a, b): return a if __name__=="__main__": - print('Euclidean mod: ', euclid_mod(64 * 67, 64 * 81)) - print('Euclidean sub: ', euclid_sub(128 * 12, 128 * 77)) + print '[#]\nModulus-based euclidean algorithm result:\n', euclid_mod(64 * 67, 64 * 81) + print '[#]\nSubtraction-based euclidean algorithm result:\n', euclid_sub(128 * 12, 128 * 77) diff --git a/contents/euclidean_algorithm/code/ruby/euclidean.rb b/contents/euclidean_algorithm/code/ruby/euclidean.rb index b8667ad71..b55bbd728 100644 --- a/contents/euclidean_algorithm/code/ruby/euclidean.rb +++ b/contents/euclidean_algorithm/code/ruby/euclidean.rb @@ -17,9 +17,8 @@ def gcd_minus(a, b) end a end - -p gcd_mod(12 * 6, 12 * 4) #=> 12 -p gcd_mod(9 * 667, 9 * 104) #=> 9 -p gcd_minus(12 * 6, 12 * 4) #=> 12 -p gcd_minus(9 * 667, 9 * 104) #=> 9 +print "[#]\nModulus-based euclidean algorithm result:\n" +p gcd_mod(64 * 67, 64 * 81) +print "[#]\nSubtraction-based euclidean algorithm result:\n" +p gcd_minus(128 * 12, 128 * 77) From 328e8a4f293cef11c1abe6d7e9816c4a5cce23c4 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:57:19 +0200 Subject: [PATCH 12/30] Standardize kotlin output --- contents/euclidean_algorithm/code/kotlin/Euclidean.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/kotlin/Euclidean.kt b/contents/euclidean_algorithm/code/kotlin/Euclidean.kt index 9e14c7463..4d86cbbe4 100644 --- a/contents/euclidean_algorithm/code/kotlin/Euclidean.kt +++ b/contents/euclidean_algorithm/code/kotlin/Euclidean.kt @@ -26,6 +26,8 @@ fun euclidMod(a: Int, b: Int): Int { } fun main(args: Array) { + println("[#]\nModulus-based euclidean algorithm result:") println(euclidSub(128 * 12, 128 * 77)) + println("[#]\nSubtraction-based euclidean algorithm result:") println(euclidMod(64 * 67, 64 * 81)) } From 9f95a6148e2b510607b118d337360e0b208c9163 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:57:29 +0200 Subject: [PATCH 13/30] Standardize lua output --- contents/euclidean_algorithm/code/lua/euclidean.lua | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contents/euclidean_algorithm/code/lua/euclidean.lua b/contents/euclidean_algorithm/code/lua/euclidean.lua index 6b2aa8faa..0149ffd34 100644 --- a/contents/euclidean_algorithm/code/lua/euclidean.lua +++ b/contents/euclidean_algorithm/code/lua/euclidean.lua @@ -25,8 +25,10 @@ local function euclid_mod(a, b) end local function main() - print(euclid_sub(128 * 12, 128 * 77)) + print("[#]\nModulus-based euclidean algorithm result:") print(euclid_mod(64 * 67, 64 * 81)) + print("[#]\nSubtraction-based euclidean algorithm result:") + print(euclid_sub(128 * 12, 128 * 77)) end main() From 511b4464273313afc80957dd874f22cc3dd3e670 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 05:57:34 +0200 Subject: [PATCH 14/30] Standardize matlab output Printing stuff properly seems impossible in this language, but as it is not planned to automatically matlab code anyway, the missing newlines after `[#]` won't matter. --- contents/euclidean_algorithm/code/matlab/euclidean.m | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/matlab/euclidean.m b/contents/euclidean_algorithm/code/matlab/euclidean.m index de2a63dec..7a9b317f3 100644 --- a/contents/euclidean_algorithm/code/matlab/euclidean.m +++ b/contents/euclidean_algorithm/code/matlab/euclidean.m @@ -31,6 +31,7 @@ end function euclid() - ['gcd(520,420) via euclidSub: ',num2str(euclidSub(520,420))] - ['gcd(183,244) via euclidMod: ',num2str(euclidMod(183,244))] + ['[#] Modulus-based euclidean algorithm result: ',num2str(euclidMod(64 * 67, 64 * 81))] + + ['[#] Subtraction-based euclidean algorithm result: ',num2str(euclidSub(128 * 12, 128 * 77))] end \ No newline at end of file From 42fd666826bf07c35096f4aee93f48a93c832425 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:05:30 +0200 Subject: [PATCH 15/30] Standardize nim output --- contents/euclidean_algorithm/code/nim/euclid_algorithm.nim | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/nim/euclid_algorithm.nim b/contents/euclidean_algorithm/code/nim/euclid_algorithm.nim index e74855592..d52b8062a 100644 --- a/contents/euclidean_algorithm/code/nim/euclid_algorithm.nim +++ b/contents/euclidean_algorithm/code/nim/euclid_algorithm.nim @@ -24,5 +24,7 @@ func euclid_sub(in1, in2: int): int = result = a when isMainModule: + echo "[#]\nModulus-based euclidean algorithm result:" echo euclid_sub(64 * 67, 64 * 81) + echo "[#]\nSubtraction-based euclidean algorithm result:" echo euclid_mod(128 * 12, 128 * 77) From 3095ea80659862563cabf6c5b6ebc67d94382504 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:05:37 +0200 Subject: [PATCH 16/30] Standardize powershell output --- .../code/powershell/euclidean_algorithm.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/powershell/euclidean_algorithm.ps1 b/contents/euclidean_algorithm/code/powershell/euclidean_algorithm.ps1 index d717320c8..3e3925ed7 100644 --- a/contents/euclidean_algorithm/code/powershell/euclidean_algorithm.ps1 +++ b/contents/euclidean_algorithm/code/powershell/euclidean_algorithm.ps1 @@ -26,5 +26,5 @@ function Mod-Euclid($a, $b) { return $a } -Write-Host "Subtraction-based euclidean algorithm result: $(Mod-Euclid $(64 * 67) $(64 * 81))" -Write-Host "Modulus-based euclidean algorithm result: $(Sub-Euclid $(128 * 12) $(128 * 77))" +Write-Host "[#]`nSubtraction-based euclidean algorithm result:`n$(Mod-Euclid $(64 * 67) $(64 * 81))" +Write-Host "[#]`nModulus-based euclidean algorithm result:`n$(Sub-Euclid $(128 * 12) $(128 * 77))" From 7edccc7d213376b6c4b89305ce55c1b1e2bc2a04 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:05:47 +0200 Subject: [PATCH 17/30] Standardize rust output --- contents/euclidean_algorithm/code/rust/euclidean_example.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/rust/euclidean_example.rs b/contents/euclidean_algorithm/code/rust/euclidean_example.rs index 89b55ba22..1c9fb55f7 100644 --- a/contents/euclidean_algorithm/code/rust/euclidean_example.rs +++ b/contents/euclidean_algorithm/code/rust/euclidean_example.rs @@ -29,6 +29,6 @@ fn euclid_rem(mut a: i64, mut b: i64) -> i64 { fn main() { let chk1 = euclid_rem(64 * 67, 64 * 81); let chk2 = euclid_sub(128 * 12, 128 * 77); - println!("{}", chk1); - println!("{}", chk2); + println!("[#]\nModulus-based euclidean algorithm result:\n{}", chk1); + println!("[#]\nSubtraction-based euclidean algorithm result:\n{}", chk2); } From cd1def46cd2c109b6ce512cb194daddb55847d2a Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:07:15 +0200 Subject: [PATCH 18/30] Standardize scala output. Fixed bug in the original implementation (euclid -> euclid_sub). --- .../euclidean_algorithm/code/scala/euclidean.scala | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/contents/euclidean_algorithm/code/scala/euclidean.scala b/contents/euclidean_algorithm/code/scala/euclidean.scala index bc3fe103a..25079e603 100644 --- a/contents/euclidean_algorithm/code/scala/euclidean.scala +++ b/contents/euclidean_algorithm/code/scala/euclidean.scala @@ -3,8 +3,8 @@ object Euclid { def euclid_sub(a: Int, b: Int): Int = (Math.abs(a), Math.abs(b)) match { case (0, _) | (_, 0) => 0 - case (x, y) if x < y => euclid(x, y - x) - case (x, y) if x > y => euclid(x - y, y) + case (x, y) if x < y => euclid_sub(x, y - x) + case (x, y) if x > y => euclid_sub(x - y, y) case _ => a } @@ -15,8 +15,10 @@ object Euclid { } def main(args: Array[String]): Unit = { - println(euclid_sub(151 * 899, 151 * 182)) - println(euclid_mod(151 * 899, 151 * 182)) + println("[#]\nModulus-based euclidean algorithm result:") + println(euclid_mod(64 * 67, 64 * 81)) + println("[#]\nSubtraction-based euclidean algorithm result:") + println(euclid_sub(128 * 12, 128 * 77)) } } From f5f95fba4effba95a29bce8bda0886ad8faaf7be Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:07:49 +0200 Subject: [PATCH 19/30] Standardize php output --- contents/euclidean_algorithm/code/php/euclidean.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/php/euclidean.php b/contents/euclidean_algorithm/code/php/euclidean.php index 52aac08c9..cd13e9d74 100644 --- a/contents/euclidean_algorithm/code/php/euclidean.php +++ b/contents/euclidean_algorithm/code/php/euclidean.php @@ -29,7 +29,7 @@ function euclid_mod(int $a, int $b): int return $a; } -printf('Euclidean mod: %s', euclid_mod(64 * 67, 64 * 81)); +printf('[#]'.PHP_EOL.'Modulus-based euclidean algorithm result:'.PHP_EOL.'%s', euclid_mod(64 * 67, 64 * 81)); echo PHP_EOL; -printf('Euclidean sub: %s', euclid_sub(128 * 12, 128 * 77)); +printf('[#]'.PHP_EOL.'Subtraction-based euclidean algorithm result:'.PHP_EOL.'%s', euclid_sub(128 * 12, 128 * 77)); echo PHP_EOL; From 18dc8ad17ed2b21852c67eb4182e68f2780fac17 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:10:33 +0200 Subject: [PATCH 20/30] Standardize swift output --- .../euclidean_algorithm/code/swift/euclidean_algorithm.swift | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift b/contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift index 7b43959ad..9c2c71448 100644 --- a/contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift +++ b/contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift @@ -27,7 +27,9 @@ func euclidMod(a: Int, b: Int) -> Int { } func main() { + print("[#]\nModulus-based euclidean algorithm result:") print(euclidMod(a: 64 * 67, b: 64 * 81)) + print("[#]\nSubtraction-based euclidean algorithm result:") print(euclidSub(a: 128 * 12, b: 128 * 77)) } From 7b186657889a5854e8035237ff3737e0d2f419bf Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:13:55 +0200 Subject: [PATCH 21/30] Fix kotlin printing order --- contents/euclidean_algorithm/code/kotlin/Euclidean.kt | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/contents/euclidean_algorithm/code/kotlin/Euclidean.kt b/contents/euclidean_algorithm/code/kotlin/Euclidean.kt index 4d86cbbe4..855afcd59 100644 --- a/contents/euclidean_algorithm/code/kotlin/Euclidean.kt +++ b/contents/euclidean_algorithm/code/kotlin/Euclidean.kt @@ -27,7 +27,7 @@ fun euclidMod(a: Int, b: Int): Int { fun main(args: Array) { println("[#]\nModulus-based euclidean algorithm result:") - println(euclidSub(128 * 12, 128 * 77)) - println("[#]\nSubtraction-based euclidean algorithm result:") println(euclidMod(64 * 67, 64 * 81)) -} + println("[#]\nSubtraction-based euclidean algorithm result:") + println(euclidSub(128 * 12, 128 * 77)) +} \ No newline at end of file From 1f77cc29aad548251b508a543d63d9daa6118c09 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Tue, 12 Oct 2021 06:15:15 +0200 Subject: [PATCH 22/30] Use python3 printing style --- .../euclidean_algorithm/code/python/euclidean_example.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/python/euclidean_example.py b/contents/euclidean_algorithm/code/python/euclidean_example.py index 37c9278f7..03d51aa4b 100644 --- a/contents/euclidean_algorithm/code/python/euclidean_example.py +++ b/contents/euclidean_algorithm/code/python/euclidean_example.py @@ -27,5 +27,7 @@ def euclid_sub(a, b): return a if __name__=="__main__": - print '[#]\nModulus-based euclidean algorithm result:\n', euclid_mod(64 * 67, 64 * 81) - print '[#]\nSubtraction-based euclidean algorithm result:\n', euclid_sub(128 * 12, 128 * 77) + print('[#]\nModulus-based euclidean algorithm result:'), + print(euclid_mod(64 * 67, 64 * 81)) + print('[#]\nSubtraction-based euclidean algorithm result:') + print(euclid_sub(128 * 12, 128 * 77)) From 84210b0619d6fa037e030c0bef8c0fed59e1145b Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Sat, 6 Nov 2021 03:22:40 +0100 Subject: [PATCH 23/30] Merge master --- .devcontainer/Dockerfile | 54 +++--- .gitignore | 7 + CONTRIBUTORS.md | 4 +- SConscript | 10 ++ SConstruct | 20 +++ contents/IFS/code/c/SConscript | 6 + .../approximate_counting.md | 2 + .../code/c++/approximate_counting.cpp | 6 +- .../approximate_counting/code/c/SConscript | 6 + .../code/c/approximate_counting.c | 82 +++++++++ .../code/julia/approximate_counting.jl | 6 +- .../code/python/approximate_counting.py | 6 +- contents/barnsley/code/c/SConscript | 6 + contents/computus/code/c/SConscript | 6 + contents/convolutions/1d/1d.md | 14 ++ .../1d/code/python/1d_convolution.py | 53 ++++++ .../code/julia/convolutional_theorem.jl | 15 +- .../code/python/convolutional_theorem.py | 19 +++ .../convolutional_theorem.md | 15 ++ contents/cooley_tukey/code/c/SConscript | 6 + contents/cooley_tukey/cooley_tukey.md | 6 - .../euclidean_algorithm/code/c/SConscript | 6 + .../code/scheme/euclidalg.ss | 3 +- .../euclidean_algorithm.md | 6 +- contents/flood_fill/code/c/SConscript | 6 + contents/flood_fill/code/cpp/flood_fill.cpp | 156 ++++++++++++++++++ contents/flood_fill/flood_fill.md | 10 ++ .../forward_euler_method/code/c/SConscript | 6 + .../gaussian_elimination/code/c/SConscript | 6 + contents/graham_scan/code/c/SConscript | 6 + contents/huffman_encoding/code/c/SConscript | 6 + .../huffman_encoding/code/julia/huffman.jl | 39 +++-- contents/jarvis_march/code/c/SConscript | 6 + .../monte_carlo_integration/code/c/SConscript | 6 + .../code/clojure/monte_carlo.clj | 5 +- .../code/racket/monte_carlo.rkt | 39 +++-- .../monte_carlo_integration.md | 4 +- 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 +- .../split-operator_method/code/c/SConscript | 6 + .../stable_marriage_problem/code/c/SConscript | 6 + .../stacks_and_queues/code/java/Queue.java | 71 ++++++++ .../stacks_and_queues/code/java/Stack.java | 72 ++++++++ .../stacks_and_queues/stacks_and_queues.md | 4 + contents/thomas_algorithm/code/c/SConscript | 6 + .../tree_traversal/code/c++/tree_example.cpp | 33 ++-- contents/tree_traversal/code/c/SConscript | 6 + .../tree_traversal/code/c/tree_traversal.c | 38 ++++- .../code/clisp/tree-traversal.lisp | 19 ++- .../code/coconut/tree_traversal.coco | 21 +-- .../code/crystal/tree-traversal.cr | 50 ++---- .../tree_traversal/code/csharp/Program.cs | 27 +-- contents/tree_traversal/code/csharp/Tree.cs | 44 ++--- .../tree_traversal/code/csharp/code.csproj | 9 + .../code/golang/treetraversal.go | 40 +++-- .../code/haskell/TreeTraversal.hs | 47 +++--- .../tree_traversal/code/java/MainClass.java | 34 ++++ contents/tree_traversal/code/java/Tree.java | 80 ++++----- .../tree_traversal/code/javascript/tree.js | 52 ++++-- contents/tree_traversal/code/julia/Tree.jl | 34 ++-- .../code/php/tree_traversal.php | 44 ++--- .../code/python/Tree_example.py | 99 ----------- .../code/python/tree_traversal.py | 103 ++++++++++++ contents/tree_traversal/code/rust/tree.rs | 35 ++-- .../code/smalltalk/tree_traversal.st | 81 +++++++++ contents/tree_traversal/code/swift/tree.swift | 31 ++-- contents/tree_traversal/tree_traversal.md | 84 ++++++---- .../verlet_integration/code/asm-x64/verlet.s | 6 +- .../verlet_integration/code/c++/verlet.cpp | 10 +- contents/verlet_integration/code/c/SConscript | 6 + contents/verlet_integration/code/c/verlet.c | 10 +- .../verlet_integration/code/clisp/verlet.lisp | 10 +- .../code/fortran/verlet.f90 | 15 +- .../verlet_integration/code/golang/verlet.go | 10 +- .../verlet_integration/code/haskell/verlet.hs | 10 +- .../verlet_integration/code/java/Verlet.java | 10 +- .../code/javascript/verlet.js | 10 +- .../verlet_integration/code/julia/verlet.jl | 10 +- .../verlet_integration/code/kotlin/verlet.kt | 10 +- .../verlet_integration/code/nim/verlet.nim | 10 +- .../verlet_integration/code/python/verlet.py | 10 +- .../verlet_integration/code/ruby/verlet.rb | 10 +- .../verlet_integration/code/rust/verlet.rs | 10 +- .../code/swift/verlet.swift | 10 +- .../verlet_integration/verlet_integration.md | 40 ----- 89 files changed, 1440 insertions(+), 781 deletions(-) create mode 100644 SConscript create mode 100644 SConstruct create mode 100644 contents/IFS/code/c/SConscript create mode 100644 contents/approximate_counting/code/c/SConscript create mode 100644 contents/approximate_counting/code/c/approximate_counting.c create mode 100644 contents/barnsley/code/c/SConscript create mode 100644 contents/computus/code/c/SConscript create mode 100644 contents/convolutions/1d/code/python/1d_convolution.py create mode 100644 contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py create mode 100644 contents/cooley_tukey/code/c/SConscript create mode 100644 contents/euclidean_algorithm/code/c/SConscript create mode 100644 contents/flood_fill/code/c/SConscript create mode 100644 contents/flood_fill/code/cpp/flood_fill.cpp create mode 100644 contents/forward_euler_method/code/c/SConscript create mode 100644 contents/gaussian_elimination/code/c/SConscript create mode 100644 contents/graham_scan/code/c/SConscript create mode 100644 contents/huffman_encoding/code/c/SConscript create mode 100644 contents/jarvis_march/code/c/SConscript create mode 100644 contents/monte_carlo_integration/code/c/SConscript 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 create mode 100644 contents/split-operator_method/code/c/SConscript create mode 100644 contents/stable_marriage_problem/code/c/SConscript create mode 100644 contents/stacks_and_queues/code/java/Queue.java create mode 100644 contents/stacks_and_queues/code/java/Stack.java create mode 100644 contents/thomas_algorithm/code/c/SConscript create mode 100644 contents/tree_traversal/code/c/SConscript create mode 100644 contents/tree_traversal/code/csharp/code.csproj create mode 100644 contents/tree_traversal/code/java/MainClass.java delete mode 100644 contents/tree_traversal/code/python/Tree_example.py create mode 100644 contents/tree_traversal/code/python/tree_traversal.py create mode 100644 contents/tree_traversal/code/smalltalk/tree_traversal.st create mode 100644 contents/verlet_integration/code/c/SConscript diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index e014b404b..ee273e5af 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -6,7 +6,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} # [Optional] Uncomment this section to install additional OS packages. RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ - && apt-get -y install --no-install-recommends build-essential software-properties-common xz-utils g++ sbcl julia python3 python3-pip python3-dev ghc openjdk-11-jdk rustc libssl-dev gfortran libxml2-dev libyaml-dev libgmp-dev libz-dev libncurses5 gnuplot nodejs npm lua5.3 ocaml php ruby-full gnu-smalltalk scratch + && apt-get -y install --no-install-recommends build-essential software-properties-common xz-utils g++ sbcl julia python3 python3-pip python3-dev ghc openjdk-11-jdk rustc libssl-dev gfortran libxml2-dev libyaml-dev libgmp-dev libz-dev libncurses5 gnuplot nodejs npm lua5.3 ocaml php ruby-full gnu-smalltalk scratch libfftw3-dev # Setup Crystal RUN echo 'deb http://download.opensuse.org/repositories/devel:/languages:/crystal/xUbuntu_20.04/ /' | sudo tee /etc/apt/sources.list.d/devel:languages:crystal.list @@ -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,36 +55,35 @@ 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 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 (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 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 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 - -# Setup Scheme -## Use: https://github.com/ashinn/chibi-scheme +# 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 Scratch ## 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 -## ? +# To run vim script commands use `/usr/bin/vim -c ":source %" ` +RUN export DEBIAN_FRONTEND=noninteractive && apt-get -y install --no-install-recommends vim # Setup whitespace ## ? @@ -94,13 +92,15 @@ RUN sudo add-apt-repository 'deb https://cloud.r-project.org/bin/linux/ubuntu fo ## https://github.com/elm/compiler/blob/master/installers/linux/README.md # Setup V -## https://github.com/vlang/v/blob/master/doc/docs.md - +RUN mkdir -p ~/vlang && wget https://github.com/vlang/v/releases/download/weekly.2021.44/v_linux.zip -O ~/vlang/vlang.zip && \ + unzip ~/vlang/vlang.zip -d ~/vlang +ENV PATH=$PATH:~/vlang/v # 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 +RUN pip install wheel matplotlib numpy coconut scons RUN sudo sh -c 'npm install -g typescript' + diff --git a/.gitignore b/.gitignore index db26e0ad0..231da8ea1 100644 --- a/.gitignore +++ b/.gitignore @@ -517,3 +517,10 @@ vscode/ # aspell *.bak + +# SCons intermidiate files +.sconsign.dblite +*.o + +# SCons build directory +build/ diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index fb8ecde19..82f3c173a 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -51,7 +51,7 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Vincent Zalzal - Jonathan D B Van Schenck - James Goytia -- Amaras +- Sammy Plat - Jonathan Dönszelmann - Ishaan Verma - Delphi1024 @@ -59,3 +59,5 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Mahdi Sarikhani - Ridham177 - Hugo Salou +- Dimitri Belopopsky ++ Henrik Abel Christensen diff --git a/SConscript b/SConscript new file mode 100644 index 000000000..be18b33d3 --- /dev/null +++ b/SConscript @@ -0,0 +1,10 @@ +from pathlib import Path + +Import('*') + +for p in Path('contents').iterdir(): + if (q := (p / 'code')).exists(): + for path in q.iterdir(): + if path.stem in languages: + env.SConscript(path / 'SConscript', exports='env', + must_exist=0) diff --git a/SConstruct b/SConstruct new file mode 100644 index 000000000..df000f732 --- /dev/null +++ b/SConstruct @@ -0,0 +1,20 @@ +""" +SCons top-level build description (SConstruct) for the Arcane Algorithm Achive + +This provides Builder objects for each of the language implementations in the AAA; however, this work cannot be considered exhaustive until every language has been covered. + +Currently, the aim is to provide a way to compile or copy the implementation files to the build directory, as well as to provide ways to run them and capture their output. + +To run the compilation for all implmeentations in one language, e.g. Rust, run the command `scons build/c`, and the resulting executables will be available in the `cuild/c` directory, each in their respective algorithm directory, containing the executable.""" + +from pathlib import Path + +env = Environment() + +# Add other languages here when you want to add language targets +languages = ['c'] + +env.C = env.Program + +SConscript('SConscript', exports='env languages') + diff --git a/contents/IFS/code/c/SConscript b/contents/IFS/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/IFS/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.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.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/SConscript b/contents/approximate_counting/code/c/SConscript new file mode 100644 index 000000000..34a951e7f --- /dev/null +++ b/contents/approximate_counting/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') 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..da44334a7 --- /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, 10%% error\n"); + test_approximation_count(100, 1000, 30, 0.1); + printf("testing 12345, a = 10, 10%% error\n"); + test_approximation_count(100, 12345, 10, 0.1); + 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) diff --git a/contents/barnsley/code/c/SConscript b/contents/barnsley/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/barnsley/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/computus/code/c/SConscript b/contents/computus/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/computus/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/convolutions/1d/1d.md b/contents/convolutions/1d/1d.md index d5d77652b..9a2e652d1 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: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. @@ -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: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. @@ -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: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 @@ -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: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. @@ -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:25-25, 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-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. @@ -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) diff --git a/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl b/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl index 31a504eaf..9016bf3d8 100644 --- a/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl +++ b/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl @@ -1,4 +1,5 @@ using FFTW +using LinearAlgebra using DelimitedFiles # using the convolutional theorem @@ -8,11 +9,9 @@ end function main() - # Random distribution in x - x = rand(100) - - # Gaussian signals - y = [exp(-((i-50)/100)^2/.01) for i = 1:100] + # sawtooth functions for x and y + x = [float(i)/200 for i = 1:200] + y = [float(i)/200 for i = 1:200] # Normalization is not strictly necessary, but good practice normalize!(x) @@ -22,6 +21,10 @@ function main() fft_output = convolve_fft(x, y) # outputting convolutions to different files for plotting in external code - writedlm("fft.dat", fft_output) + # note: we are outputting just the real component because the imaginary + # component is virtually 0 + writedlm("fft.dat", real(fft_output)) end + +main() 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 0063c992c..1034f2018 100644 --- a/contents/convolutions/convolutional_theorem/convolutional_theorem.md +++ b/contents/convolutions/convolutional_theorem/convolutional_theorem.md @@ -39,11 +39,21 @@ Also note that the Fourier Transform is a periodic or cyclic operation, so there ## Example Code +For this example code, we will be using two sawtooth functions as we did in the chapter on [one-dimensional convolutions](../1d/1d.md): + {% 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: + +

+ +

+ @@ -54,6 +64,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). diff --git a/contents/cooley_tukey/code/c/SConscript b/contents/cooley_tukey/code/c/SConscript new file mode 100644 index 000000000..2cd13de37 --- /dev/null +++ b/contents/cooley_tukey/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS=['m', 'fftw3']) diff --git a/contents/cooley_tukey/cooley_tukey.md b/contents/cooley_tukey/cooley_tukey.md index d67d4dbd2..67309b5d2 100644 --- a/contents/cooley_tukey/cooley_tukey.md +++ b/contents/cooley_tukey/cooley_tukey.md @@ -81,8 +81,6 @@ For some reason, though, putting code to this transformation really helped me fi [import:7-13, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import:6-12, lang:"python"](code/python/fft.py) -{% sample lang="scratch" %} -[import:4-13, lang:"julia"](code/julia/fft.jl) {% sample lang="asm-x64" %} [import:15-74, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} @@ -136,8 +134,6 @@ In the end, the code looks like: [import:15-28, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import:15-26, lang:"python"](code/python/fft.py) -{% sample lang="scratch" %} -[import:16-32, lang:"julia"](code/julia/fft.jl) {% sample lang="asm-x64" %} [import:76-165, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} @@ -251,8 +247,6 @@ Note: I implemented this in Julia because the code seems more straightforward in [import, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import, lang:"python"](code/python/fft.py) -{% sample lang="scratch" %} -Some rather impressive scratch code was submitted by Jie and can be found here: https://scratch.mit.edu/projects/37759604/#editor {% sample lang="asm-x64" %} [import, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} diff --git a/contents/euclidean_algorithm/code/c/SConscript b/contents/euclidean_algorithm/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/euclidean_algorithm/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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) + diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index 82aa64a2a..f44c3acb7 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -56,7 +56,7 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two {% sample lang="scala" %} [import:3-8, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import:3-14, lang="lisp"](code/racket/euclidean_algorithm.rkt) +[import:3-14, lang="racket"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import:8-19, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} @@ -146,7 +146,7 @@ Modern implementations, though, often use the modulus operator (%) like so {% sample lang="scala" %} [import:10-14, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import:16-24, lang="lisp"](code/racket/euclidean_algorithm.rkt) +[import:16-24, lang="racket"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import:1-6, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} @@ -252,7 +252,7 @@ and modulo method: {% sample lang="scala" %} [import, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import, lang="lisp"](code/racket/euclidean_algorithm.rkt) +[import, lang="racket"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} diff --git a/contents/flood_fill/code/c/SConscript b/contents/flood_fill/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/flood_fill/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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" %} diff --git a/contents/forward_euler_method/code/c/SConscript b/contents/forward_euler_method/code/c/SConscript new file mode 100644 index 000000000..34a951e7f --- /dev/null +++ b/contents/forward_euler_method/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') diff --git a/contents/gaussian_elimination/code/c/SConscript b/contents/gaussian_elimination/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/gaussian_elimination/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/graham_scan/code/c/SConscript b/contents/graham_scan/code/c/SConscript new file mode 100644 index 000000000..34a951e7f --- /dev/null +++ b/contents/graham_scan/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') diff --git a/contents/huffman_encoding/code/c/SConscript b/contents/huffman_encoding/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/huffman_encoding/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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 diff --git a/contents/jarvis_march/code/c/SConscript b/contents/jarvis_march/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/jarvis_march/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/monte_carlo_integration/code/c/SConscript b/contents/monte_carlo_integration/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/monte_carlo_integration/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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" %} 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. diff --git a/contents/split-operator_method/code/c/SConscript b/contents/split-operator_method/code/c/SConscript new file mode 100644 index 000000000..2cd13de37 --- /dev/null +++ b/contents/split-operator_method/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS=['m', 'fftw3']) diff --git a/contents/stable_marriage_problem/code/c/SConscript b/contents/stable_marriage_problem/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/stable_marriage_problem/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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 %} diff --git a/contents/thomas_algorithm/code/c/SConscript b/contents/thomas_algorithm/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/thomas_algorithm/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index 9f2dd80e1..71a84c686 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 << "[#]\nRecursive DFS:\n"; dfs_recursive(root); - std::cout << "DFS post order recursive:\n"; + std::cout << '\n'; + std::cout << "[#]\nRecursive 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 << "[#]\nStack-based DFS:\n"; dfs_stack(root); - std::cout << "BFS queue:\n"; + std::cout << '\n'; + std::cout << "[#]\nQueue-based BFS:\n"; bfs_queue(root); + std::cout << '\n'; + std::cout << "[#]\nRecursive Inorder DFS for Binary Tree:\n"; + dfs_recursive_inorder_btree(binary_root); + std::cout << '\n'; return 0; } diff --git a/contents/tree_traversal/code/c/SConscript b/contents/tree_traversal/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/tree_traversal/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index 7fed9a16c..16be536c8 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,31 @@ void bfs_queue(struct node n) { } int main() { - struct node root = create_tree(3, 3); + struct node root = create_tree(2, 3); + + printf("[#]\nRecursive DFS:\n"); + dfs_recursive(root); + printf("\n"); + + printf("[#]\nRecursive Postorder DFS:\n"); + dfs_recursive_postorder(root); + printf("\n"); + + printf("[#]\nStack-based DFS:\n"); + dfs_stack(root); + printf("\n"); + + printf("[#]\nQueue-based BFS:\n"); bfs_queue(root); + printf("\n"); + destroy_tree(root); + struct node root_binary = create_tree(3, 2); + printf("[#]\nRecursive Inorder DFS for Binary Tree:\n"); + dfs_recursive_inorder_btree(root_binary); + printf("\n"); + + destroy_tree(root_binary); return 0; } diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 417a6f242..8c74db43b 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 "~%") diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index c7433fea2..776708f6e 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,33 +59,28 @@ 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:") + print("[#]\nRecursive 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("[#]\nRecursive 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("[#]\nStack-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("[#]\nQueue-based BFS:") bfs_queue(tree) print() # And a binary tree for testing binary_tree = create_tree(3, 2) - # Should print: 1 2 1 3 1 2 1 - print("Recursive Inorder 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 e3556d8eb..e63dbbb7e 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 "[#]\nRecursive DFS:" dfs_recursive root puts - puts "Using recursive DFS with post-order traversal:" + puts "[#]\nRecursive Postorder DFS:" dfs_recursive_postorder root puts - puts "Using stack-based DFS:" + puts "[#]\nStack-based DFS:" dfs_stack root puts - puts "Using queue-based BFS:" + puts "[#]\nQueue-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 "[#]\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 aa2df0485..0fc35c547 100644 --- a/contents/tree_traversal/code/csharp/Program.cs +++ b/contents/tree_traversal/code/csharp/Program.cs @@ -1,4 +1,3 @@ -// submitted by Julian Schacher (jspp) using System; namespace TreeTraversal @@ -7,23 +6,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("[#]\nRecursive DFS:"); tree.DFSRecursive(); - Console.WriteLine("DFSStack:"); + Console.WriteLine(); + + Console.WriteLine("[#]\nRecursive Postorder DFS:"); + tree.DFSRecursivePostorder(); + Console.WriteLine(); + + Console.WriteLine("[#]\nStack-based DFS:"); tree.DFSStack(); - Console.WriteLine("BFSQueue:"); + Console.WriteLine(); + + Console.WriteLine("[#]\nQueue-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("[#]\nRecursive 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..28df47c91 100644 --- a/contents/tree_traversal/code/csharp/Tree.cs +++ b/contents/tree_traversal/code/csharp/Tree.cs @@ -1,4 +1,3 @@ -// submitted by Julian Schacher (jspp) using System; using System.Collections.Generic; @@ -11,23 +10,23 @@ public class Tree public Tree(int depthCount, int childrenCount) { - this.Id = 1; + Id = 1; - 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)); + _children.Add(new Tree(Id * 10 + i + 1, depthCount - 1, childrenCount)); } } private Tree(int id, int depthCount, int childrenCount) { - this.Id = id; + Id = id; if (!(depthCount <= 1)) { for (int i = 0; i < childrenCount; i++) - this._children.Add(new Tree(this.Id * 10 + i + 1, depthCount - 1, childrenCount)); + _children.Add(new Tree(Id * 10 + i + 1, depthCount - 1, childrenCount)); } } @@ -37,7 +36,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 +52,7 @@ void DFSRecursivePostorder(Tree tree) foreach (var c in tree._children) DFSRecursivePostorder(c); - Console.WriteLine(tree.Id); + Console.Write(tree.Id + " "); } } @@ -61,20 +60,25 @@ public void DFSRecursiveInorderBinary() { DFSRecursiveInorderBinary(this); - // This assumes only 2 children void DFSRecursiveInorderBinary(Tree tree) { - if (tree._children.Count > 2) - throw new Exception("Not binary tree!"); - - if (tree._children.Count > 0) + switch (tree._children.Count) { - DFSRecursiveInorderBinary(tree._children[0]); - Console.WriteLine(tree.Id); - DFSRecursiveInorderBinary(tree._children[1]); + case 2: + DFSRecursiveInorderBinary(tree._children[0]); + Console.Write(tree.Id + " "); + DFSRecursiveInorderBinary(tree._children[1]); + break; + case 1: + DFSRecursiveInorderBinary(tree._children[0]); + Console.Write(tree.Id + " "); + break; + case 0: + Console.Write(tree.Id + " "); + break; + default: + throw new Exception("Not binary tree!"); } - else - Console.WriteLine(tree.Id); } } @@ -85,7 +89,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 +104,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 + + + diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index 548f552f7..fb5142712 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) } @@ -16,22 +16,22 @@ func dfsRecursive(n *node) { func dfsRecursivePostorder(n *node) { for _, child := range n.children { - dfsRecursive(child) + dfsRecursivePostorder(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("[#]\nRecursive DFS:") dfsRecursive(root) - fmt.Println("DFS post order recursive:") + fmt.Println() + + fmt.Println("[#]\nRecursive Postorder DFS:") dfsRecursivePostorder(root) - fmt.Println("DFS inorder binary tree:") - dfsRecursiveInorderBtree(binTree) - fmt.Println("DFS stack:") + fmt.Println() + + fmt.Println("[#]\nStack-based DFS:") dfsStack(root) - fmt.Println("BFS queue:") + fmt.Println() + + fmt.Println("[#]\nQueue-based BFS:") bfsQueue(root) + fmt.Println() + + 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 389dc0900..1f9d27db8 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 "[#]\nRecursive DFS:" + putStrLn $ showNodes $ dfs testTree + putStrLn "[#]\nRecursive Postorder DFS:" + putStrLn $ showNodes $ dfsPostOrder testTree + putStrLn "[#]\nStack-based DFS:" + putStrLn $ showNodes $ dfsStack testTree + putStrLn "[#]\nQueue-based BFS:" + putStrLn $ showNodes $ bfs testTree + 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 new file mode 100644 index 000000000..d7c062c03 --- /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("[#]\nRecursive DFS:"); + tree.dfsRecursive(); + System.out.println(); + + 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("[#]\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(); + + tree = new Tree(3, 2); + System.out.println("[#]\nRecursive 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 1dee7d9d1..93e508f6c 100644 --- a/contents/tree_traversal/code/java/Tree.java +++ b/contents/tree_traversal/code/java/Tree.java @@ -1,6 +1,5 @@ -// submitted by xam4lor import java.util.ArrayList; -import java.util.PriorityQueue; +import java.util.LinkedList; import java.util.Queue; import java.util.Stack; @@ -9,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); } @@ -19,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); @@ -37,7 +36,7 @@ private void dfsRecursivePostOrder(Node node) { } // Here we are doing something ... - System.out.println(node.id); + System.out.print(node.id + " "); } @@ -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.print(node.id + " "); + dfsRecursiveInOrderBinary(node.children.get(1)); + break; + case 1: + dfsRecursiveInOrderBinary(node.children.get(0)); + System.out.print(node.id + " "); + break; + case 0: + System.out.print(node.id + " "); + break; + default: + System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!"); } } @@ -69,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) { @@ -79,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) { @@ -96,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); } } @@ -126,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("[#]\nRecursive Postorder DFS:"); + tree.dfsRecursivePostOrder(); + System.out.println(); + - System.out.println("Using stack-based DFS :"); + 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(); } - } diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index b6705bfdd..1fbffa02a 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -10,13 +10,21 @@ function createTree(rows, children) { } function dfsPreorder(tree) { - console.log(tree.id); + if (!tree) { + return; + } + + process.stdout.write(tree.id + " "); tree.children.forEach(dfsPreorder); } function dfsPostorder(tree) { + if (!tree) { + return; + } + tree.children.forEach(dfsPostorder); - console.log(tree.id); + process.stdout.write(tree.id + " "); } function dfsInorder(tree) { @@ -24,20 +32,29 @@ 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) { 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 +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("[#]\nRecursive DFS:"); dfsPreorder(root); +console.log(); +console.log("[#]\nRecursive Postorder DFS:"); dfsPostorder(root); +console.log(); +console.log("[#]\nStack-based DFS:"); dfsIterative(root); +console.log(); +console.log("[#]\nQueue-based BFS:"); bfs(root); +console.log(); +const root_binary = createTree(3, 2); +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 d44345e8d..7382fdad0 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) + 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... - println(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]) - println(n.ID) + print(n.ID, " ") DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - println(n.ID) + print(n.ID, " ") elseif (length(n.children) == 0) - println(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) - println(first(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) - println(first(q).ID) + print(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("[#]\nRecursive DFS:") DFS_recursive(root); + println() - println("Using recursive DFS with post-order traversal:") + println("[#]\nRecursive Postorder DFS:") DFS_recursive_postorder(root); + println() - println("Using stack-based DFS:") + println("[#]\nStack-based DFS:") DFS_stack(root); + println() - println("Using queue-based BFS:") + println("[#]\nQueue-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("[#]\nRecursive Inorder DFS for Binary Tree:") DFS_recursive_inorder_btree(root_binary) + println() end main() diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index fde55046a..3c829977b 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 '[#]' . PHP_EOL . 'Recursive DFS:' . PHP_EOL; TreeTraversal::DFSRecursive($node); +echo PHP_EOL; -echo 'DFS Recursive Postorder:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Recursive Postorder DFS:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); +echo PHP_EOL; -echo 'DFS Stack:' . PHP_EOL; +echo '[#]' . PHP_EOL . 'Stack-based DFS:' . PHP_EOL; TreeTraversal::DFSStack($node); +echo PHP_EOL; -echo 'DFS Queue:' . PHP_EOL; +echo '[#]' . PHP_EOL . '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 '[#]' . 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_example.py b/contents/tree_traversal/code/python/Tree_example.py deleted file mode 100644 index 67dd516a3..000000000 --- a/contents/tree_traversal/code/python/Tree_example.py +++ /dev/null @@ -1,99 +0,0 @@ -class Node: - def __init__(self): - self.data = None - self.children = [] - - -def create_tree(node, num_row, num_child): - node.data = num_row - - if num_row > 0: - for i in range(num_child): - child = create_tree(Node(), num_row-1, num_child) - node.children.append(child) - - return node - - -def DFS_recursive(node): - if node.data != None: - print(node.data) - - for child in node.children: - DFS_recursive(child) - - -def DFS_recursive_postorder(node): - for child in node.children: - 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): - if (len(node.children) == 2): - DFS_recursive_inorder_btree(node.children[0]) - print(node.data) - DFS_recursive_inorder_btree(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) - else: - print("Not a binary tree!") - - -def DFS_stack(node): - stack = [] - stack.append(node) - - temp = None - - while len(stack) > 0: - print(stack[-1].data) - temp = stack.pop() - - for child in temp.children: - stack.append(child) - - -def BFS_queue(node): - queue = [] - queue.append(node) - - temp = None - - while len(queue) > 0: - print(queue[0].data) - temp = queue.pop(0) - - for child in temp.children: - queue.append(child) - - -def main(): - tree = create_tree(Node(), 3, 3) - - print("Recursive:") - DFS_recursive(tree) - - print("Recursive Postorder:") - DFS_recursive_postorder(tree) - - print("Stack:") - DFS_stack(tree) - - print("Queue:") - BFS_queue(tree) - - binaryTree = create_tree(Node(), 3, 2) - - print("Recursive Inorder Binary Tree:") - DFS_recursive_inorder_btree(binaryTree) - -if __name__ == '__main__': - main() - diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py new file mode 100644 index 000000000..735837bdd --- /dev/null +++ b/contents/tree_traversal/code/python/tree_traversal.py @@ -0,0 +1,103 @@ +class Node: + def __init__(self): + self.data = None + self.children = [] + +def create_tree(node, num_row, num_child): + node.data = num_row + + if num_row > 0: + for i in range(num_child): + child = create_tree(Node(), num_row-1, num_child) + node.children.append(child) + + return node + + +def dfs_recursive(node): + if node.data != None: + print(node.data, end=' ') + + for child in node.children: + dfs_recursive(child) + + +def dfs_recursive_postorder(node): + for child in node.children: + dfs_recursive_postorder(child) + + if node.data != None: + 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: + dfs_recursive_inorder_btree(node.children[0]) + print(node.data, end=' ') + dfs_recursive_inorder_btree(node.children[1]) + elif len(node.children) == 1: + dfs_recursive_inorder_btree(node.children[0]) + print(node.data, end=' ') + elif len(node.children) == 0: + print(node.data, end=' ') + else: + print("Not a binary tree!") + + +def dfs_stack(node): + stack = [] + stack.append(node) + + temp = None + + while len(stack) > 0: + print(stack[-1].data, end=' ') + temp = stack.pop() + + for child in temp.children: + stack.append(child) + + +def bfs_queue(node): + queue = [] + queue.append(node) + + temp = None + + while len(queue) > 0: + print(queue[0].data, end=' ') + temp = queue.pop(0) + + for child in temp.children: + queue.append(child) + + +def main(): + tree = create_tree(Node(), 2, 3) + + print("[#]\nRecursive DFS:") + dfs_recursive(tree) + print() + + print("[#]\nRecursive Postorder DFS:") + dfs_recursive_postorder(tree) + print() + + print("[#]\nStack-based DFS:") + dfs_stack(tree) + print() + + print("[#]\nQueue-based BFS:") + bfs_queue(tree) + print() + + binary_tree = create_tree(Node(), 3, 2) + + print("[#]\nRecursive Inorder DFS for Binary Tree:") + dfs_recursive_inorder_btree(binary_tree) + print() + +if __name__ == '__main__': + main() + diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index f281e1a8c..60e833858 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!("[#]\nRecursive DFS:"); dfs_recursive(&root); + println!(); - println!("Stack DFS:"); + println!("[#]\nRecursive Postorder DFS:"); + dfs_recursive_postorder(&root); + println!(); + + println!("[#]\nStack-based DFS:"); dfs_stack(&root); + println!(); - println!("Queue BFS:"); + println!("[#]\nQueue-based BFS:"); bfs_queue(&root); + println!(); - println!("Recursive post-order DFS:"); - dfs_recursive_postorder(&root); - - println!("Recursive in-order DFS BTree:"); + 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/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/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index e286c8fb0..ae64315ec 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("[#]\nRecursive DFS:") dfsRecursive(node: root) + print() - print("Using recursive postorder DFS:") + print("[#]\nRecursive Postorder DFS:") dfsRecursivePostOrder(node: root) + print() - print("Using stack-based DFS:") + print("[#]\nStack-based DFS:") dfsStack(node: root) + print() - print("Using queue-based BFS:") + print("[#]\nQueue-based BFS:") bfsQueue(node: root) + print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("Using In-order DFS:") + print("[#]\nRecursive Inorder DFS for Binary Tree:") dfsRecursiveInOrderBinary(node: rootBinary) + print() } main() diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index e03f09652..4b6c5b762 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -8,16 +8,16 @@ Trees are naturally recursive data structures, and because of this, we cannot ac {% sample lang="cpp" %} [import:12-15, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:7-11, lang:"csharp"](code/csharp/Tree.cs) +[import:6-10, lang:"csharp"](code/csharp/Tree.cs) {% 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. {% 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" %}

@@ -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" %} @@ -54,15 +56,15 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="cpp" %} [import:17-24, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:34-45, lang:"csharp"](code/csharp/Tree.cs) +[import:33-44, lang:"csharp"](code/csharp/Tree.cs) {% 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) +[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" %}

@@ -70,13 +72,15 @@ 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" %} -[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" %} +[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" %} @@ -108,15 +112,15 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="cpp" %} [import:26-31, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:47-58, lang:"csharp"](code/csharp/Tree.cs) +[import:46-57, lang:"csharp"](code/csharp/Tree.cs) {% 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) +[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" %}

@@ -124,13 +128,15 @@ 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" %} -[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" %} +[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" %} @@ -142,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 %}

@@ -157,15 +163,15 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="cpp" %} [import:34-52 lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:60-79, lang:"csharp"](code/csharp/Tree.cs) +[import:59-83, lang:"csharp"](code/csharp/Tree.cs) {% 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) +[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" %}

@@ -173,13 +179,15 @@ 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" %} -[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" %} +[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" %} @@ -215,15 +223,15 @@ In code, it looks like this: {% sample lang="cpp" %} [import:55-70, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:81-94, lang:"csharp"](code/csharp/Tree.cs) +[import:85-98, lang:"csharp"](code/csharp/Tree.cs) {% 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) +[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" %}

@@ -231,13 +239,15 @@ 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" %} -[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" %} +[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" %} @@ -266,15 +276,15 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="cpp" %} [import:73-86, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:96-109, lang:"csharp"](code/csharp/Tree.cs) +[import:100-113, lang:"csharp"](code/csharp/Tree.cs) {% 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) +[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" %}

@@ -282,13 +292,15 @@ 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" %} -[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" %} +[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" %} @@ -333,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/) @@ -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" %} 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/SConscript b/contents/verlet_integration/code/c/SConscript new file mode 100644 index 000000000..fd696f9ce --- /dev/null +++ b/contents/verlet_integration/code/c/SConscript @@ -0,0 +1,6 @@ +Import('*') +from pathlib import Path + +dirname = Path.cwd().parents[1].stem + +env.C(f'#/build/c/{dirname}', Glob('*.c')) 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)") } diff --git a/contents/verlet_integration/verlet_integration.md b/contents/verlet_integration/verlet_integration.md index 402a7ba1b..08fe4a4b3 100644 --- a/contents/verlet_integration/verlet_integration.md +++ b/contents/verlet_integration/verlet_integration.md @@ -42,15 +42,6 @@ Here is what it looks like in code: [import:1-10, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:14-21, lang:"haskell"](code/haskell/verlet.hs) -{% sample lang="scratch" %} -Unfortunately, this has not yet been implemented in scratch, so here's Julia code: -[import:1-13, lang:"julia"](code/julia/verlet.jl) -{% sample lang="m" %} -Unfortunately, this has not yet been implemented in matlab, so here's Julia code: -[import:1-13, lang:"julia"](code/julia/verlet.jl) -{% sample lang="LabVIEW" %} -Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: -[import:1-13, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:1-14, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -100,15 +91,6 @@ However, the error for this is $$\mathcal{O}(\Delta t)$$, which is quite poor, b [import:12-23, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:23-28, lang:"haskell"](code/haskell/verlet.hs) -{% sample lang="scratch" %} -Unfortunately, this has not yet been implemented in scratch, so here's Julia code: -[import:15-31, lang:"julia"](code/julia/verlet.jl) -{% sample lang="m" %} -Unfortunately, this has not yet been implemented in matlab, so here's Julia code: -[import:15-31, lang:"julia"](code/julia/verlet.jl) -{% sample lang="LabVIEW" %} -Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: -[import:15-31, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:16-32, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -172,15 +154,6 @@ Here is the velocity Verlet method in code: [import:25-34, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:30-35, lang:"haskell"](code/haskell/verlet.hs) -{% sample lang="scratch" %} -Unfortunately, this has not yet been implemented in scratch, so here's Julia code: -[import:33-45, lang:"julia"](code/julia/verlet.jl) -{% sample lang="m" %} -Unfortunately, this has not yet been implemented in matlab, so here's Julia code: -[import:33-45, lang:"julia"](code/julia/verlet.jl) -{% sample lang="LabVIEW" %} -Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: -[import:33-45, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:34-45, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -230,19 +203,6 @@ Both of these methods work simply by iterating timestep-by-timestep and can be w [import, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import, lang:"haskell"](code/haskell/verlet.hs) -{% sample lang="scratch" %} -Submitted by Jie -

- -

-Link: [https://scratch.mit.edu/projects/173039394/](https://scratch.mit.edu/projects/173039394/) -{% sample lang="m" %} -[import, lang:"matlab"](code/matlab/verlet.m) -{% sample lang="LabVIEW" %} -Submitted by P. Mekhail -

- -

{% sample lang="js" %} [import, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} From c0d00fa029156e8c3bed4982323034af134e2242 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Sat, 6 Nov 2021 05:23:37 +0100 Subject: [PATCH 24/30] Revert "Merge master" This reverts commit 84210b0619d6fa037e030c0bef8c0fed59e1145b. --- .devcontainer/Dockerfile | 54 +++--- .gitignore | 7 - CONTRIBUTORS.md | 4 +- SConscript | 10 -- SConstruct | 20 --- contents/IFS/code/c/SConscript | 6 - .../approximate_counting.md | 2 - .../code/c++/approximate_counting.cpp | 6 +- .../approximate_counting/code/c/SConscript | 6 - .../code/c/approximate_counting.c | 82 --------- .../code/julia/approximate_counting.jl | 6 +- .../code/python/approximate_counting.py | 6 +- contents/barnsley/code/c/SConscript | 6 - contents/computus/code/c/SConscript | 6 - contents/convolutions/1d/1d.md | 14 -- .../1d/code/python/1d_convolution.py | 53 ------ .../code/julia/convolutional_theorem.jl | 15 +- .../code/python/convolutional_theorem.py | 19 --- .../convolutional_theorem.md | 15 -- contents/cooley_tukey/code/c/SConscript | 6 - contents/cooley_tukey/cooley_tukey.md | 6 + .../euclidean_algorithm/code/c/SConscript | 6 - .../code/scheme/euclidalg.ss | 3 +- .../euclidean_algorithm.md | 6 +- contents/flood_fill/code/c/SConscript | 6 - contents/flood_fill/code/cpp/flood_fill.cpp | 156 ------------------ contents/flood_fill/flood_fill.md | 10 -- .../forward_euler_method/code/c/SConscript | 6 - .../gaussian_elimination/code/c/SConscript | 6 - contents/graham_scan/code/c/SConscript | 6 - contents/huffman_encoding/code/c/SConscript | 6 - .../huffman_encoding/code/julia/huffman.jl | 39 ++--- contents/jarvis_march/code/c/SConscript | 6 - .../monte_carlo_integration/code/c/SConscript | 6 - .../code/clojure/monte_carlo.clj | 5 +- .../code/racket/monte_carlo.rkt | 39 ++--- .../monte_carlo_integration.md | 4 +- 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 +- .../split-operator_method/code/c/SConscript | 6 - .../stable_marriage_problem/code/c/SConscript | 6 - .../stacks_and_queues/code/java/Queue.java | 71 -------- .../stacks_and_queues/code/java/Stack.java | 72 -------- .../stacks_and_queues/stacks_and_queues.md | 4 - contents/thomas_algorithm/code/c/SConscript | 6 - .../tree_traversal/code/c++/tree_example.cpp | 33 ++-- contents/tree_traversal/code/c/SConscript | 6 - .../tree_traversal/code/c/tree_traversal.c | 38 +---- .../code/clisp/tree-traversal.lisp | 19 +-- .../code/coconut/tree_traversal.coco | 21 ++- .../code/crystal/tree-traversal.cr | 50 ++++-- .../tree_traversal/code/csharp/Program.cs | 27 ++- contents/tree_traversal/code/csharp/Tree.cs | 44 +++-- .../tree_traversal/code/csharp/code.csproj | 9 - .../code/golang/treetraversal.go | 40 ++--- .../code/haskell/TreeTraversal.hs | 47 +++--- .../tree_traversal/code/java/MainClass.java | 34 ---- contents/tree_traversal/code/java/Tree.java | 80 +++++---- .../tree_traversal/code/javascript/tree.js | 52 ++---- contents/tree_traversal/code/julia/Tree.jl | 34 ++-- .../code/php/tree_traversal.php | 44 ++--- .../code/python/Tree_example.py | 99 +++++++++++ .../code/python/tree_traversal.py | 103 ------------ contents/tree_traversal/code/rust/tree.rs | 35 ++-- .../code/smalltalk/tree_traversal.st | 81 --------- contents/tree_traversal/code/swift/tree.swift | 31 ++-- contents/tree_traversal/tree_traversal.md | 84 ++++------ .../verlet_integration/code/asm-x64/verlet.s | 6 +- .../verlet_integration/code/c++/verlet.cpp | 10 +- contents/verlet_integration/code/c/SConscript | 6 - contents/verlet_integration/code/c/verlet.c | 10 +- .../verlet_integration/code/clisp/verlet.lisp | 10 +- .../code/fortran/verlet.f90 | 15 +- .../verlet_integration/code/golang/verlet.go | 10 +- .../verlet_integration/code/haskell/verlet.hs | 10 +- .../verlet_integration/code/java/Verlet.java | 10 +- .../code/javascript/verlet.js | 10 +- .../verlet_integration/code/julia/verlet.jl | 10 +- .../verlet_integration/code/kotlin/verlet.kt | 10 +- .../verlet_integration/code/nim/verlet.nim | 10 +- .../verlet_integration/code/python/verlet.py | 10 +- .../verlet_integration/code/ruby/verlet.rb | 10 +- .../verlet_integration/code/rust/verlet.rs | 10 +- .../code/swift/verlet.swift | 10 +- .../verlet_integration/verlet_integration.md | 40 +++++ 89 files changed, 781 insertions(+), 1440 deletions(-) delete mode 100644 SConscript delete mode 100644 SConstruct delete mode 100644 contents/IFS/code/c/SConscript delete mode 100644 contents/approximate_counting/code/c/SConscript delete mode 100644 contents/approximate_counting/code/c/approximate_counting.c delete mode 100644 contents/barnsley/code/c/SConscript delete mode 100644 contents/computus/code/c/SConscript delete mode 100644 contents/convolutions/1d/code/python/1d_convolution.py delete mode 100644 contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py delete mode 100644 contents/cooley_tukey/code/c/SConscript delete mode 100644 contents/euclidean_algorithm/code/c/SConscript delete mode 100644 contents/flood_fill/code/c/SConscript delete mode 100644 contents/flood_fill/code/cpp/flood_fill.cpp delete mode 100644 contents/forward_euler_method/code/c/SConscript delete mode 100644 contents/gaussian_elimination/code/c/SConscript delete mode 100644 contents/graham_scan/code/c/SConscript delete mode 100644 contents/huffman_encoding/code/c/SConscript delete mode 100644 contents/jarvis_march/code/c/SConscript delete mode 100644 contents/monte_carlo_integration/code/c/SConscript create mode 100644 contents/quantum_systems/code/c++/energy.cpp create mode 100644 contents/quantum_systems/code/c/energy.c create mode 100644 contents/quantum_systems/code/haskell/Energy.hs create mode 100644 contents/quantum_systems/code/julia/energy.jl create mode 100644 contents/quantum_systems/code/python/energy.py delete mode 100644 contents/split-operator_method/code/c/SConscript delete mode 100644 contents/stable_marriage_problem/code/c/SConscript delete mode 100644 contents/stacks_and_queues/code/java/Queue.java delete mode 100644 contents/stacks_and_queues/code/java/Stack.java delete mode 100644 contents/thomas_algorithm/code/c/SConscript delete mode 100644 contents/tree_traversal/code/c/SConscript delete mode 100644 contents/tree_traversal/code/csharp/code.csproj delete mode 100644 contents/tree_traversal/code/java/MainClass.java create mode 100644 contents/tree_traversal/code/python/Tree_example.py delete mode 100644 contents/tree_traversal/code/python/tree_traversal.py delete mode 100644 contents/tree_traversal/code/smalltalk/tree_traversal.st delete mode 100644 contents/verlet_integration/code/c/SConscript diff --git a/.devcontainer/Dockerfile b/.devcontainer/Dockerfile index ee273e5af..e014b404b 100644 --- a/.devcontainer/Dockerfile +++ b/.devcontainer/Dockerfile @@ -6,7 +6,7 @@ FROM mcr.microsoft.com/vscode/devcontainers/base:0-${VARIANT} # [Optional] Uncomment this section to install additional OS packages. RUN apt-get update && export DEBIAN_FRONTEND=noninteractive \ - && apt-get -y install --no-install-recommends build-essential software-properties-common xz-utils g++ sbcl julia python3 python3-pip python3-dev ghc openjdk-11-jdk rustc libssl-dev gfortran libxml2-dev libyaml-dev libgmp-dev libz-dev libncurses5 gnuplot nodejs npm lua5.3 ocaml php ruby-full gnu-smalltalk scratch libfftw3-dev + && apt-get -y install --no-install-recommends build-essential software-properties-common xz-utils g++ sbcl julia python3 python3-pip python3-dev ghc openjdk-11-jdk rustc libssl-dev gfortran libxml2-dev libyaml-dev libgmp-dev libz-dev libncurses5 gnuplot nodejs npm lua5.3 ocaml php ruby-full gnu-smalltalk scratch # Setup Crystal RUN echo 'deb http://download.opensuse.org/repositories/devel:/languages:/crystal/xUbuntu_20.04/ /' | sudo tee /etc/apt/sources.list.d/devel:languages:crystal.list @@ -31,10 +31,11 @@ RUN sudo sh -c 'sudo dpkg -i packages-microsoft-prod.deb' RUN sudo sh -c 'rm packages-microsoft-prod.deb' # Setup D Lang -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/ +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 # 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' @@ -55,35 +56,36 @@ ENV PATH=$PATH:/usr/local/kotlinc/bin # Setup Matlab # ?????? This is a licensed language??? -# 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 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 -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 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 R 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 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 Racket +## Use: https://ubunlog.com/en/racket-install-ubuntu-programming-language + +# Setup Scheme +## Use: https://github.com/ashinn/chibi-scheme # Setup Scratch ## 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 -# To run vim script commands use `/usr/bin/vim -c ":source %" ` -RUN export DEBIAN_FRONTEND=noninteractive && apt-get -y install --no-install-recommends vim +## ? # Setup whitespace ## ? @@ -92,15 +94,13 @@ RUN export DEBIAN_FRONTEND=noninteractive && apt-get -y install --no-install-rec ## https://github.com/elm/compiler/blob/master/installers/linux/README.md # Setup V -RUN mkdir -p ~/vlang && wget https://github.com/vlang/v/releases/download/weekly.2021.44/v_linux.zip -O ~/vlang/vlang.zip && \ - unzip ~/vlang/vlang.zip -d ~/vlang -ENV PATH=$PATH:~/vlang/v +## https://github.com/vlang/v/blob/master/doc/docs.md + # 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 racket + && apt-get -y install --no-install-recommends crystal dart nim powershell scala dotnet-sdk-5.0 r-base -RUN pip install wheel matplotlib numpy coconut scons +RUN pip install wheel matplotlib numpy coconut RUN sudo sh -c 'npm install -g typescript' - diff --git a/.gitignore b/.gitignore index 231da8ea1..db26e0ad0 100644 --- a/.gitignore +++ b/.gitignore @@ -517,10 +517,3 @@ vscode/ # aspell *.bak - -# SCons intermidiate files -.sconsign.dblite -*.o - -# SCons build directory -build/ diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 82f3c173a..fb8ecde19 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -51,7 +51,7 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Vincent Zalzal - Jonathan D B Van Schenck - James Goytia -- Sammy Plat +- Amaras - Jonathan Dönszelmann - Ishaan Verma - Delphi1024 @@ -59,5 +59,3 @@ This file lists everyone, who contributed to this repo and wanted to show up her - Mahdi Sarikhani - Ridham177 - Hugo Salou -- Dimitri Belopopsky -+ Henrik Abel Christensen diff --git a/SConscript b/SConscript deleted file mode 100644 index be18b33d3..000000000 --- a/SConscript +++ /dev/null @@ -1,10 +0,0 @@ -from pathlib import Path - -Import('*') - -for p in Path('contents').iterdir(): - if (q := (p / 'code')).exists(): - for path in q.iterdir(): - if path.stem in languages: - env.SConscript(path / 'SConscript', exports='env', - must_exist=0) diff --git a/SConstruct b/SConstruct deleted file mode 100644 index df000f732..000000000 --- a/SConstruct +++ /dev/null @@ -1,20 +0,0 @@ -""" -SCons top-level build description (SConstruct) for the Arcane Algorithm Achive - -This provides Builder objects for each of the language implementations in the AAA; however, this work cannot be considered exhaustive until every language has been covered. - -Currently, the aim is to provide a way to compile or copy the implementation files to the build directory, as well as to provide ways to run them and capture their output. - -To run the compilation for all implmeentations in one language, e.g. Rust, run the command `scons build/c`, and the resulting executables will be available in the `cuild/c` directory, each in their respective algorithm directory, containing the executable.""" - -from pathlib import Path - -env = Environment() - -# Add other languages here when you want to add language targets -languages = ['c'] - -env.C = env.Program - -SConscript('SConscript', exports='env languages') - diff --git a/contents/IFS/code/c/SConscript b/contents/IFS/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/IFS/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/approximate_counting/approximate_counting.md b/contents/approximate_counting/approximate_counting.md index 654721844..f63d7db43 100644 --- a/contents/approximate_counting/approximate_counting.md +++ b/contents/approximate_counting/approximate_counting.md @@ -360,8 +360,6 @@ 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.cpp b/contents/approximate_counting/code/c++/approximate_counting.cpp index 53f4641af..7f3f1a16c 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, 10% error " + std::cout << "testing 1,000, a = 30, 1% error " << test_approximate_count(100, 1000, 30, 0.1) << "\n"; - std::cout << "testing 12,345, a = 10, 10% error " + std::cout << "testing 12,345, a = 10, 1% 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, 20% error " + std::cout << "testing 222,222, a = 0.5, 10% error " << test_approximate_count(100, 222222, 0.5, 0.2) << "\n"; } diff --git a/contents/approximate_counting/code/c/SConscript b/contents/approximate_counting/code/c/SConscript deleted file mode 100644 index 34a951e7f..000000000 --- a/contents/approximate_counting/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') diff --git a/contents/approximate_counting/code/c/approximate_counting.c b/contents/approximate_counting/code/c/approximate_counting.c deleted file mode 100644 index da44334a7..000000000 --- a/contents/approximate_counting/code/c/approximate_counting.c +++ /dev/null @@ -1,82 +0,0 @@ -#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, 10%% error\n"); - test_approximation_count(100, 1000, 30, 0.1); - printf("testing 12345, a = 10, 10%% error\n"); - test_approximation_count(100, 12345, 10, 0.1); - 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 c6cf3b223..36b07651e 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, 10% error") + println("testing 1,000, a = 30, 1% error") test_approximate_count(100, 1000, 30, 0.1) - println("testing 12,345, a = 10, 10% error") + println("testing 12,345, a = 10, 1% 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, 20% error") + println("testing 222,222, a = 0.5, 10% 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 0088debcc..eb31b2b24 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, 10% error") +print("testing 1,000, a = 30, 1% error") test_approximate_count(100, 1000, 30, 0.1) -print("testing 12,345, a = 10, 10% error") +print("testing 12,345, a = 10, 1% error") test_approximate_count(100, 12345, 10, 0.1) -print("testing 222,222, a = 0.5, 20% error") +print("testing 222,222, a = 0.5, 10% error") test_approximate_count(100, 222222, 0.5, 0.2) diff --git a/contents/barnsley/code/c/SConscript b/contents/barnsley/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/barnsley/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/computus/code/c/SConscript b/contents/computus/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/computus/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/convolutions/1d/1d.md b/contents/convolutions/1d/1d.md index 9a2e652d1..d5d77652b 100644 --- a/contents/convolutions/1d/1d.md +++ b/contents/convolutions/1d/1d.md @@ -56,8 +56,6 @@ 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: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. @@ -191,8 +189,6 @@ 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: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. @@ -203,8 +199,6 @@ 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: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 @@ -214,8 +208,6 @@ 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: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. @@ -226,8 +218,6 @@ 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:25-25, lang:"python"](code/python/1d_convolution.py) {% endmethod %} Here, `j` counts from `i-length(filter)` to `i`. @@ -262,8 +252,6 @@ 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-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. @@ -281,8 +269,6 @@ 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 deleted file mode 100644 index e77e68d09..000000000 --- a/contents/convolutions/1d/code/python/1d_convolution.py +++ /dev/null @@ -1,53 +0,0 @@ -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) diff --git a/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl b/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl index 9016bf3d8..31a504eaf 100644 --- a/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl +++ b/contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl @@ -1,5 +1,4 @@ using FFTW -using LinearAlgebra using DelimitedFiles # using the convolutional theorem @@ -9,9 +8,11 @@ end function main() - # sawtooth functions for x and y - x = [float(i)/200 for i = 1:200] - y = [float(i)/200 for i = 1:200] + # Random distribution in x + x = rand(100) + + # Gaussian signals + y = [exp(-((i-50)/100)^2/.01) for i = 1:100] # Normalization is not strictly necessary, but good practice normalize!(x) @@ -21,10 +22,6 @@ function main() fft_output = convolve_fft(x, y) # outputting convolutions to different files for plotting in external code - # note: we are outputting just the real component because the imaginary - # component is virtually 0 - writedlm("fft.dat", real(fft_output)) + writedlm("fft.dat", fft_output) end - -main() diff --git a/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py b/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py deleted file mode 100644 index f64f44a1d..000000000 --- a/contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py +++ /dev/null @@ -1,19 +0,0 @@ -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 1034f2018..0063c992c 100644 --- a/contents/convolutions/convolutional_theorem/convolutional_theorem.md +++ b/contents/convolutions/convolutional_theorem/convolutional_theorem.md @@ -39,21 +39,11 @@ Also note that the Fourier Transform is a periodic or cyclic operation, so there ## Example Code -For this example code, we will be using two sawtooth functions as we did in the chapter on [one-dimensional convolutions](../1d/1d.md): - {% 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: - -

- -

- @@ -64,11 +54,6 @@ 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). diff --git a/contents/cooley_tukey/code/c/SConscript b/contents/cooley_tukey/code/c/SConscript deleted file mode 100644 index 2cd13de37..000000000 --- a/contents/cooley_tukey/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS=['m', 'fftw3']) diff --git a/contents/cooley_tukey/cooley_tukey.md b/contents/cooley_tukey/cooley_tukey.md index 67309b5d2..d67d4dbd2 100644 --- a/contents/cooley_tukey/cooley_tukey.md +++ b/contents/cooley_tukey/cooley_tukey.md @@ -81,6 +81,8 @@ For some reason, though, putting code to this transformation really helped me fi [import:7-13, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import:6-12, lang:"python"](code/python/fft.py) +{% sample lang="scratch" %} +[import:4-13, lang:"julia"](code/julia/fft.jl) {% sample lang="asm-x64" %} [import:15-74, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} @@ -134,6 +136,8 @@ In the end, the code looks like: [import:15-28, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import:15-26, lang:"python"](code/python/fft.py) +{% sample lang="scratch" %} +[import:16-32, lang:"julia"](code/julia/fft.jl) {% sample lang="asm-x64" %} [import:76-165, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} @@ -247,6 +251,8 @@ Note: I implemented this in Julia because the code seems more straightforward in [import, lang:"haskell"](code/haskell/fft.hs) {% sample lang="py" %} [import, lang:"python"](code/python/fft.py) +{% sample lang="scratch" %} +Some rather impressive scratch code was submitted by Jie and can be found here: https://scratch.mit.edu/projects/37759604/#editor {% sample lang="asm-x64" %} [import, lang:"asm-x64"](code/asm-x64/fft.s) {% sample lang="js" %} diff --git a/contents/euclidean_algorithm/code/c/SConscript b/contents/euclidean_algorithm/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/euclidean_algorithm/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/euclidean_algorithm/code/scheme/euclidalg.ss b/contents/euclidean_algorithm/code/scheme/euclidalg.ss index 959ebdeca..3d891ba73 100644 --- a/contents/euclidean_algorithm/code/scheme/euclidalg.ss +++ b/contents/euclidean_algorithm/code/scheme/euclidalg.ss @@ -12,5 +12,4 @@ (euclid-mod b (modulo a b)))) (display (euclid-mod (* 64 67) (* 64 81))) (newline) -(display (euclid-sub (* 128 12) (* 128 77))) (newline) - +(display (euclid-sub (* 64 12) (* 64 27))) (newline) diff --git a/contents/euclidean_algorithm/euclidean_algorithm.md b/contents/euclidean_algorithm/euclidean_algorithm.md index f44c3acb7..82aa64a2a 100644 --- a/contents/euclidean_algorithm/euclidean_algorithm.md +++ b/contents/euclidean_algorithm/euclidean_algorithm.md @@ -56,7 +56,7 @@ The algorithm is a simple way to find the *greatest common divisor* (GCD) of two {% sample lang="scala" %} [import:3-8, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import:3-14, lang="racket"](code/racket/euclidean_algorithm.rkt) +[import:3-14, lang="lisp"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import:8-19, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} @@ -146,7 +146,7 @@ Modern implementations, though, often use the modulus operator (%) like so {% sample lang="scala" %} [import:10-14, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import:16-24, lang="racket"](code/racket/euclidean_algorithm.rkt) +[import:16-24, lang="lisp"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import:1-6, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} @@ -252,7 +252,7 @@ and modulo method: {% sample lang="scala" %} [import, lang="scala"](code/scala/euclidean.scala) {% sample lang="racket" %} -[import, lang="racket"](code/racket/euclidean_algorithm.rkt) +[import, lang="lisp"](code/racket/euclidean_algorithm.rkt) {% sample lang="ruby" %} [import, lang="ruby"](code/ruby/euclidean.rb) {% sample lang="st" %} diff --git a/contents/flood_fill/code/c/SConscript b/contents/flood_fill/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/flood_fill/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/flood_fill/code/cpp/flood_fill.cpp b/contents/flood_fill/code/cpp/flood_fill.cpp deleted file mode 100644 index 918566809..000000000 --- a/contents/flood_fill/code/cpp/flood_fill.cpp +++ /dev/null @@ -1,156 +0,0 @@ -#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 4c7e5936e..185050fe1 100644 --- a/contents/flood_fill/flood_fill.md +++ b/contents/flood_fill/flood_fill.md @@ -90,8 +90,6 @@ 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" %} @@ -112,8 +110,6 @@ 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" %} @@ -129,8 +125,6 @@ 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" %} @@ -174,8 +168,6 @@ 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" %} @@ -258,8 +250,6 @@ 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" %} diff --git a/contents/forward_euler_method/code/c/SConscript b/contents/forward_euler_method/code/c/SConscript deleted file mode 100644 index 34a951e7f..000000000 --- a/contents/forward_euler_method/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') diff --git a/contents/gaussian_elimination/code/c/SConscript b/contents/gaussian_elimination/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/gaussian_elimination/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/graham_scan/code/c/SConscript b/contents/graham_scan/code/c/SConscript deleted file mode 100644 index 34a951e7f..000000000 --- a/contents/graham_scan/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') diff --git a/contents/huffman_encoding/code/c/SConscript b/contents/huffman_encoding/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/huffman_encoding/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/huffman_encoding/code/julia/huffman.jl b/contents/huffman_encoding/code/julia/huffman.jl index e01fd1dfd..593d4b4f8 100644 --- a/contents/huffman_encoding/code/julia/huffman.jl +++ b/contents/huffman_encoding/code/julia/huffman.jl @@ -1,5 +1,3 @@ -using Test - # This is for the PriorityQueue using DataStructures @@ -15,6 +13,8 @@ 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,11 +33,7 @@ end # This outputs encoding Dict to be used for encoding function create_codebook(n::Node) codebook = Dict{Char,String}() - if isa(n, Leaf) - codebook[n.key]="0" - else - codebook_recurse!(n, "", codebook) - end + codebook_recurse!(n, "", codebook) return codebook end @@ -89,19 +85,14 @@ function decode(huffman_tree::Node, bitstring::String) current = huffman_tree final_string = "" for i in bitstring - 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 + if (i == '1') + current = current.left else - final_string *= string(huffman_tree.key) + current = current.right + end + if (!isbranch(current)) + final_string = final_string * string(current.key) + current = huffman_tree end end @@ -111,13 +102,11 @@ 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) - return final_string + println(bitstring) + println(final_string) end -@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 +two_pass_huffman("bibbity bobbity") diff --git a/contents/jarvis_march/code/c/SConscript b/contents/jarvis_march/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/jarvis_march/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/monte_carlo_integration/code/c/SConscript b/contents/monte_carlo_integration/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/monte_carlo_integration/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/monte_carlo_integration/code/clojure/monte_carlo.clj b/contents/monte_carlo_integration/code/clojure/monte_carlo.clj index de517e56c..f66baef67 100644 --- a/contents/monte_carlo_integration/code/clojure/monte_carlo.clj +++ b/contents/monte_carlo_integration/code/clojure/monte_carlo.clj @@ -8,11 +8,9 @@ (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" @@ -24,12 +22,11 @@ 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 0278e7ed6..0f652db93 100755 --- a/contents/monte_carlo_integration/code/racket/monte_carlo.rkt +++ b/contents/monte_carlo_integration/code/racket/monte_carlo.rkt @@ -1,25 +1,22 @@ -#lang racket/base +#lang racket +(define (in_circle x y) + (< (+ (sqr x) (sqr y)) 1) + ) -(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) +(define (monte_carlo_pi n) + (* (/ (local ((define (monte_carlo* 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) + ) + -(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)))) +(display (monte_carlo_pi 1000)) diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index cf5640ffa..ac6895404 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:6-8, lang:"racket"](code/racket/monte_carlo.rkt) +[import:2-4, lang:"lisp"](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:"racket"](code/racket/monte_carlo.rkt) +[import, lang:"lisp"](code/racket/monte_carlo.rkt) {% sample lang="scala" %} [import, lang:"scala"](code/scala/monte_carlo.scala) {% sample lang="lisp" %} diff --git a/contents/quantum_systems/code/c++/energy.cpp b/contents/quantum_systems/code/c++/energy.cpp new file mode 100644 index 000000000..15a58bd01 --- /dev/null +++ b/contents/quantum_systems/code/c++/energy.cpp @@ -0,0 +1,59 @@ +#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 new file mode 100644 index 000000000..9086ffcd5 --- /dev/null +++ b/contents/quantum_systems/code/c/energy.c @@ -0,0 +1,61 @@ +#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 new file mode 100644 index 000000000..a024fd139 --- /dev/null +++ b/contents/quantum_systems/code/haskell/Energy.hs @@ -0,0 +1,14 @@ +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 new file mode 100644 index 000000000..3efce0cb7 --- /dev/null +++ b/contents/quantum_systems/code/julia/energy.jl @@ -0,0 +1,18 @@ +# 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 new file mode 100644 index 000000000..328fa9950 --- /dev/null +++ b/contents/quantum_systems/code/python/energy.py @@ -0,0 +1,17 @@ +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 a7a762ca5..a74c22068 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:114-132, lang:"julia"](../split-operator_method/code/julia/split_op.jl) +[import, lang:"julia"](code/julia/energy.jl) {% sample lang="hs" %} -[import:75-82, lang:"haskell"](../split-operator_method/code/haskell/splitOp.hs) +[import, lang:"haskell"](code/haskell/Energy.hs) {% sample lang="c" %} -[import:150-184, lang:"c"](../split-operator_method/code/c/split_op.c) +[import:29-, lang:"c"](code/c/energy.c) {% sample lang="cpp" %} -[import:158-189, lang:"cpp"](../split-operator_method/code/c++/split_op.cpp) +[import:26-, lang:"cpp"](code/c++/energy.cpp) {% sample lang="py" %} -[import:98-112, lang:"python"](../split-operator_method/code/python/split_op.py) +[import:4-17, lang:"python"](code/python/energy.py) {% endmethod %} This calculation will be used in many different simulations of quantum systems to check our results. diff --git a/contents/split-operator_method/code/c/SConscript b/contents/split-operator_method/code/c/SConscript deleted file mode 100644 index 2cd13de37..000000000 --- a/contents/split-operator_method/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS=['m', 'fftw3']) diff --git a/contents/stable_marriage_problem/code/c/SConscript b/contents/stable_marriage_problem/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/stable_marriage_problem/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/stacks_and_queues/code/java/Queue.java b/contents/stacks_and_queues/code/java/Queue.java deleted file mode 100644 index bb349ec6d..000000000 --- a/contents/stacks_and_queues/code/java/Queue.java +++ /dev/null @@ -1,71 +0,0 @@ -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 deleted file mode 100644 index 2d65a0e59..000000000 --- a/contents/stacks_and_queues/code/java/Stack.java +++ /dev/null @@ -1,72 +0,0 @@ -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 89a77be9a..11c7088f7 100644 --- a/contents/stacks_and_queues/stacks_and_queues.md +++ b/contents/stacks_and_queues/stacks_and_queues.md @@ -18,16 +18,12 @@ 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 %} diff --git a/contents/thomas_algorithm/code/c/SConscript b/contents/thomas_algorithm/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/thomas_algorithm/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/tree_traversal/code/c++/tree_example.cpp b/contents/tree_traversal/code/c++/tree_example.cpp index 71a84c686..9f2dd80e1 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 << ' '; + std::cout << n.value << '\n'; 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 << ' '; + std::cout << n.value << '\n'; } @@ -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 << ' '; + std::cout << n.value << '\n'; dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - std::cout << n.value << ' '; + std::cout << n.value << '\n'; break; case 0: - std::cout << n.value << ' '; + std::cout << n.value << '\n'; 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 << ' '; + std::cout << temp.value << '\n'; 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 << ' '; + std::cout << temp.value << '\n'; for (auto const& child : temp.children) { queue.push(&child); } @@ -100,23 +100,18 @@ node create_tree(size_t num_row, size_t num_child) { int main() { // Creating Tree in main - auto root = create_tree(2, 3); + auto root = create_tree(3, 3); auto binary_root = create_tree(3, 2); - std::cout << "[#]\nRecursive DFS:\n"; + std::cout << "DFS recursive:\n"; dfs_recursive(root); - std::cout << '\n'; - std::cout << "[#]\nRecursive Postorder DFS:\n"; + std::cout << "DFS post order recursive:\n"; dfs_recursive_postorder(root); - std::cout << '\n'; - std::cout << "[#]\nStack-based DFS:\n"; + std::cout << "DFS inorder binary tree:\n"; + dfs_recursive_inorder_btree(binary_root); + std::cout << "DFS stack:\n"; dfs_stack(root); - std::cout << '\n'; - std::cout << "[#]\nQueue-based BFS:\n"; + std::cout << "BFS queue:\n"; bfs_queue(root); - std::cout << '\n'; - std::cout << "[#]\nRecursive Inorder DFS for Binary Tree:\n"; - dfs_recursive_inorder_btree(binary_root); - std::cout << '\n'; return 0; } diff --git a/contents/tree_traversal/code/c/SConscript b/contents/tree_traversal/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/tree_traversal/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/tree_traversal/code/c/tree_traversal.c b/contents/tree_traversal/code/c/tree_traversal.c index 16be536c8..7fed9a16c 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.id); + printf("%d\n", 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.id); + printf("%d\n", 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.id); + printf("%d\n", n.id); dfs_recursive_inorder_btree(n.children[1]); break; case 1: dfs_recursive_inorder_btree(n.children[0]); - printf("%d ", n.id); + printf("%d\n", n.id); break; case 0: - printf("%d ", n.id); + printf("%d\n", 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 ", tmp->id); + printf("%d\n", 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 ", tmp->id); + printf("%d\n", tmp->id); for (size_t i = 0; i < tmp->children_size; ++i) { enqueue(&q, &tmp->children[i]); } @@ -113,31 +113,9 @@ void bfs_queue(struct node n) { } int main() { - struct node root = create_tree(2, 3); - - printf("[#]\nRecursive DFS:\n"); - dfs_recursive(root); - printf("\n"); - - printf("[#]\nRecursive Postorder DFS:\n"); - dfs_recursive_postorder(root); - printf("\n"); - - printf("[#]\nStack-based DFS:\n"); - dfs_stack(root); - printf("\n"); - - printf("[#]\nQueue-based BFS:\n"); + struct node root = create_tree(3, 3); bfs_queue(root); - printf("\n"); - destroy_tree(root); - struct node root_binary = create_tree(3, 2); - printf("[#]\nRecursive Inorder DFS for Binary Tree:\n"); - dfs_recursive_inorder_btree(root_binary); - printf("\n"); - - destroy_tree(root_binary); return 0; } diff --git a/contents/tree_traversal/code/clisp/tree-traversal.lisp b/contents/tree_traversal/code/clisp/tree-traversal.lisp index 8c74db43b..417a6f242 100644 --- a/contents/tree_traversal/code/clisp/tree-traversal.lisp +++ b/contents/tree_traversal/code/clisp/tree-traversal.lisp @@ -58,41 +58,36 @@ (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 0) + (if (eql num-rows 1) (make-node - :data 0 + :data 1 :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 2 3)) +(defvar tree (make-tree 3 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 "~%") diff --git a/contents/tree_traversal/code/coconut/tree_traversal.coco b/contents/tree_traversal/code/coconut/tree_traversal.coco index 776708f6e..c7433fea2 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 == 0: - return Node(0, ()) + if num_rows == 1: + return Node(1, ()) else: return Node(num_rows, tuple(create_tree(num_rows-1, num_child) for _ in range(num_child))) @@ -59,28 +59,33 @@ def create_tree(num_rows, num_child): if __name__ =='__main__': # A ternary tree for testing - tree = create_tree(2, 3) + tree = create_tree(3, 3) - print("[#]\nRecursive DFS:") + # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 + print("Recursive DFS:") dfs_recursive(tree) print() - print("[#]\nRecursive Postorder DFS:") + # Should print: 1 1 1 2 1 1 1 2 1 1 1 2 3 + print("Recursive Postorder DFS:") dfs_recursive_postorder(tree) print() - print("[#]\nStack-based DFS:") + # Should print: 3 2 1 1 1 2 1 1 1 2 1 1 1 + print("Stack (DFS):") dfs_stack(tree) print() - print("[#]\nQueue-based BFS:") + # Should print: 3 2 2 2 1 1 1 1 1 1 1 1 1 + print("Queue (BFS):") bfs_queue(tree) print() # And a binary tree for testing binary_tree = create_tree(3, 2) - print("[#]\nRecursive Inorder DFS for Binary Tree:") + # Should print: 1 2 1 3 1 2 1 + print("Recursive Inorder 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 e63dbbb7e..e3556d8eb 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,28 +60,54 @@ 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 "[#]\nRecursive DFS:" + puts "Using recursive DFS:" dfs_recursive root puts - puts "[#]\nRecursive Postorder DFS:" + puts "Using recursive DFS with post-order traversal:" dfs_recursive_postorder root puts - puts "[#]\nStack-based DFS:" + puts "Using stack-based DFS:" dfs_stack root puts - puts "[#]\nQueue-based BFS:" + puts "Using 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 "[#]\nRecursive Inorder DFS for Binary Tree:" + puts "Using In-order DFS:" 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 0fc35c547..aa2df0485 100644 --- a/contents/tree_traversal/code/csharp/Program.cs +++ b/contents/tree_traversal/code/csharp/Program.cs @@ -1,3 +1,4 @@ +// submitted by Julian Schacher (jspp) using System; namespace TreeTraversal @@ -6,27 +7,23 @@ class Program { static void Main(string[] args) { - var tree = new Tree(2, 3); - Console.WriteLine("[#]\nRecursive DFS:"); + Console.WriteLine("TreeTraversal"); + var tree = new Tree(3, 3); + Console.WriteLine("DFSRecursive:"); tree.DFSRecursive(); - Console.WriteLine(); - - Console.WriteLine("[#]\nRecursive Postorder DFS:"); - tree.DFSRecursivePostorder(); - Console.WriteLine(); - - Console.WriteLine("[#]\nStack-based DFS:"); + Console.WriteLine("DFSStack:"); tree.DFSStack(); - Console.WriteLine(); - - Console.WriteLine("[#]\nQueue-based BFS:"); + Console.WriteLine("BFSQueue:"); tree.BFSQueue(); - Console.WriteLine(); + Console.WriteLine("DFSRecursivePostorder"); + tree.DFSRecursivePostorder(); + // 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("[#]\nRecursive Inorder DFS for Binary Tree:"); + Console.WriteLine("DFSRecursiveInorder (succeed)"); tree.DFSRecursiveInorderBinary(); - Console.WriteLine(); } } } diff --git a/contents/tree_traversal/code/csharp/Tree.cs b/contents/tree_traversal/code/csharp/Tree.cs index 28df47c91..e38be26fc 100644 --- a/contents/tree_traversal/code/csharp/Tree.cs +++ b/contents/tree_traversal/code/csharp/Tree.cs @@ -1,3 +1,4 @@ +// submitted by Julian Schacher (jspp) using System; using System.Collections.Generic; @@ -10,23 +11,23 @@ public class Tree public Tree(int depthCount, int childrenCount) { - Id = 1; + this.Id = 1; - if (depthCount > 0) + if (!(depthCount <= 1)) { for (int i = 0; i < childrenCount; i++) - _children.Add(new Tree(Id * 10 + i + 1, depthCount - 1, childrenCount)); + this._children.Add(new Tree(this.Id * 10 + i + 1, depthCount - 1, childrenCount)); } } private Tree(int id, int depthCount, int childrenCount) { - Id = id; + this.Id = id; if (!(depthCount <= 1)) { for (int i = 0; i < childrenCount; i++) - _children.Add(new Tree(Id * 10 + i + 1, depthCount - 1, childrenCount)); + this._children.Add(new Tree(this.Id * 10 + i + 1, depthCount - 1, childrenCount)); } } @@ -36,7 +37,7 @@ public void DFSRecursive() void DFSRecursive(Tree tree) { - Console.Write(tree.Id + " "); + Console.WriteLine(tree.Id); foreach (var c in tree._children) DFSRecursive(c); @@ -52,7 +53,7 @@ void DFSRecursivePostorder(Tree tree) foreach (var c in tree._children) DFSRecursivePostorder(c); - Console.Write(tree.Id + " "); + Console.WriteLine(tree.Id); } } @@ -60,25 +61,20 @@ public void DFSRecursiveInorderBinary() { DFSRecursiveInorderBinary(this); + // This assumes only 2 children void DFSRecursiveInorderBinary(Tree tree) { - switch (tree._children.Count) + if (tree._children.Count > 2) + throw new Exception("Not binary tree!"); + + if (tree._children.Count > 0) { - case 2: - DFSRecursiveInorderBinary(tree._children[0]); - Console.Write(tree.Id + " "); - DFSRecursiveInorderBinary(tree._children[1]); - break; - case 1: - DFSRecursiveInorderBinary(tree._children[0]); - Console.Write(tree.Id + " "); - break; - case 0: - Console.Write(tree.Id + " "); - break; - default: - throw new Exception("Not binary tree!"); + DFSRecursiveInorderBinary(tree._children[0]); + Console.WriteLine(tree.Id); + DFSRecursiveInorderBinary(tree._children[1]); } + else + Console.WriteLine(tree.Id); } } @@ -89,7 +85,7 @@ public void DFSStack() while (stack.Count != 0) { - Console.Write(stack.Peek().Id + " "); + Console.WriteLine(stack.Peek().Id); var temp = stack.Pop(); foreach (var c in temp._children) @@ -104,7 +100,7 @@ public void BFSQueue() while (queue.Count != 0) { - Console.Write(queue.Peek().Id + " "); + Console.WriteLine(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 deleted file mode 100644 index 98c5e6713..000000000 --- a/contents/tree_traversal/code/csharp/code.csproj +++ /dev/null @@ -1,9 +0,0 @@ - - - - Exe - net5.0 - false - - - diff --git a/contents/tree_traversal/code/golang/treetraversal.go b/contents/tree_traversal/code/golang/treetraversal.go index fb5142712..548f552f7 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.Printf("%d ", n.id) + fmt.Println(n.id) for _, child := range n.children { dfsRecursive(child) } @@ -16,22 +16,22 @@ func dfsRecursive(n *node) { func dfsRecursivePostorder(n *node) { for _, child := range n.children { - dfsRecursivePostorder(child) + dfsRecursive(child) } - fmt.Printf("%d ", n.id) + fmt.Println(n.id) } func dfsRecursiveInorderBtree(n *node) { switch len(n.children) { case 2: dfsRecursiveInorderBtree(n.children[0]) - fmt.Printf("%d ", n.id) + fmt.Println(n.id) dfsRecursiveInorderBtree(n.children[1]) case 1: dfsRecursiveInorderBtree(n.children[0]) - fmt.Printf("%d ", n.id) + fmt.Println(n.id) case 0: - fmt.Printf("%d ", n.id) + fmt.Println(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.Printf("%d ", cur.id) + fmt.Println(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.Printf("%d ", cur.id) + fmt.Println(cur.id) queue = append(queue, cur.children...) } } @@ -74,27 +74,17 @@ func createTree(numRow, numChild int) *node { } func main() { - root := createTree(2, 3) + root := createTree(3, 3) binTree := createTree(3, 2) - fmt.Println("[#]\nRecursive DFS:") + fmt.Println("DFS recursive:") dfsRecursive(root) - fmt.Println() - - fmt.Println("[#]\nRecursive Postorder DFS:") + fmt.Println("DFS post order recursive:") dfsRecursivePostorder(root) - fmt.Println() - - fmt.Println("[#]\nStack-based DFS:") + fmt.Println("DFS inorder binary tree:") + dfsRecursiveInorderBtree(binTree) + fmt.Println("DFS stack:") dfsStack(root) - fmt.Println() - - fmt.Println("[#]\nQueue-based BFS:") + fmt.Println("BFS queue:") bfsQueue(root) - fmt.Println() - - 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 1f9d27db8..389dc0900 100644 --- a/contents/tree_traversal/code/haskell/TreeTraversal.hs +++ b/contents/tree_traversal/code/haskell/TreeTraversal.hs @@ -1,8 +1,7 @@ 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 @@ -20,7 +19,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 @@ -28,22 +27,26 @@ bfs (Node x ts) = x : go ts go [] = [] go ts = map node ts ++ go (concatMap forest 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 +toBin :: Tree a -> Tree a +toBin (Node x ts) = Node x (map toBin $ take 2 ts) main = do - let testTree = createTree 2 3 - showNodes = unwords . map show - putStrLn "[#]\nRecursive DFS:" - putStrLn $ showNodes $ dfs testTree - putStrLn "[#]\nRecursive Postorder DFS:" - putStrLn $ showNodes $ dfsPostOrder testTree - putStrLn "[#]\nStack-based DFS:" - putStrLn $ showNodes $ dfsStack testTree - putStrLn "[#]\nQueue-based BFS:" - putStrLn $ showNodes $ bfs testTree - putStrLn "[#]\nRecursive Inorder DFS for Binary Tree:" - putStrLn $ showNodes $ dfsInOrder $ createTree 3 2 + 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 [] + ] diff --git a/contents/tree_traversal/code/java/MainClass.java b/contents/tree_traversal/code/java/MainClass.java deleted file mode 100644 index d7c062c03..000000000 --- a/contents/tree_traversal/code/java/MainClass.java +++ /dev/null @@ -1,34 +0,0 @@ -//submitted by xam4lor -public class MainClass { - public static void main(String[] args) { - Tree tree = new Tree(2, 3); - - System.out.println("[#]\nRecursive DFS:"); - tree.dfsRecursive(); - System.out.println(); - - 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("[#]\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(); - - tree = new Tree(3, 2); - System.out.println("[#]\nRecursive 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 93e508f6c..1dee7d9d1 100644 --- a/contents/tree_traversal/code/java/Tree.java +++ b/contents/tree_traversal/code/java/Tree.java @@ -1,5 +1,6 @@ +// submitted by xam4lor import java.util.ArrayList; -import java.util.LinkedList; +import java.util.PriorityQueue; import java.util.Queue; import java.util.Stack; @@ -8,8 +9,8 @@ public class Tree { public Tree(int rowCount, int childrenCount) { // this.root is the root node of the Tree - this.root = new Node(rowCount); - this.createAllChildren(this.root, rowCount-1, childrenCount); + this.root = new Node(1); + this.createAllChildren(this.root, rowCount, childrenCount); } @@ -18,7 +19,7 @@ public void dfsRecursive() { } private void dfsRecursive(Node node) { - System.out.print(node.id + " "); + System.out.println(node.id); for (Node n : node.children) { dfsRecursive(n); @@ -36,7 +37,7 @@ private void dfsRecursivePostOrder(Node node) { } // Here we are doing something ... - System.out.print(node.id + " "); + System.out.println(node.id); } @@ -44,22 +45,19 @@ public void dfsRecursiveInOrderBinary() { dfsRecursiveInOrderBinary(this.root); } + // This assumes only 2 children private void dfsRecursiveInOrderBinary(Node node) { - switch (node.children.size()) { - case 2: - dfsRecursiveInOrderBinary(node.children.get(0)); - System.out.print(node.id + " "); - dfsRecursiveInOrderBinary(node.children.get(1)); - break; - case 1: - dfsRecursiveInOrderBinary(node.children.get(0)); - System.out.print(node.id + " "); - break; - case 0: - System.out.print(node.id + " "); - break; - default: - System.err.println("Not a binary tree at dfsRecursiveInOrderBinary()!"); + 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); } } @@ -71,7 +69,7 @@ public void dfsStack() { Node tmp; while (stack.size() != 0) { - System.out.print(stack.peek().id + " "); + System.out.println(stack.peek().id); tmp = stack.pop(); for (Node c : tmp.children) { @@ -81,11 +79,11 @@ public void dfsStack() { } public void bfsQueue() { - Queue queue = new LinkedList(); + Queue queue = new PriorityQueue(); queue.add(this.root); while (queue.size() != 0) { - System.out.print(queue.peek().id + " "); + System.out.println(queue.peek().id); Node temp = queue.poll(); // return null if the queue is empty if (temp != null) { @@ -98,12 +96,12 @@ public void bfsQueue() { private void createAllChildren(Node node, int rowCount, int childrenCount) { - if (rowCount < 0) { + if (rowCount <= 1) { return; } for (int i = 0; i < childrenCount; i++) { - node.children.add(new Node(rowCount)); + node.children.add(new Node(node.id * 10 + i + 1)); createAllChildren(node.children.get(i), rowCount - 1, childrenCount); } } @@ -128,34 +126,32 @@ public int compareTo(Node other) { } public static void main(String[] args) { - Tree tree = new Tree(2, 3); + System.out.println("Creating Tree"); + Tree tree = new Tree(3, 3); - System.out.println("[#]\nRecursive DFS:"); + System.out.println("Using recursive DFS :"); tree.dfsRecursive(); - System.out.println(); - - System.out.println("[#]\nRecursive Postorder DFS:"); - tree.dfsRecursivePostOrder(); - System.out.println(); - - System.out.println("[#]\nStack-based DFS:"); + System.out.println("Using stack-based DFS :"); tree.dfsStack(); - System.out.println(); - - System.out.println("[#]\nQueue-based BFS:"); + System.out.println("Using queue-based BFS :"); tree.bfsQueue(); - System.out.println(); + + System.out.println("Using post-order recursive DFS :"); + tree.dfsRecursivePostOrder(); // 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("[#]\nRecursive Inorder DFS for Binary Tree:"); + System.out.println("Using in-order binary recursive DFS : (succeed)"); tree.dfsRecursiveInOrderBinary(); - System.out.println(); + + + System.out.println(""); } + } diff --git a/contents/tree_traversal/code/javascript/tree.js b/contents/tree_traversal/code/javascript/tree.js index 1fbffa02a..b6705bfdd 100644 --- a/contents/tree_traversal/code/javascript/tree.js +++ b/contents/tree_traversal/code/javascript/tree.js @@ -10,21 +10,13 @@ function createTree(rows, children) { } function dfsPreorder(tree) { - if (!tree) { - return; - } - - process.stdout.write(tree.id + " "); + console.log(tree.id); tree.children.forEach(dfsPreorder); } function dfsPostorder(tree) { - if (!tree) { - return; - } - tree.children.forEach(dfsPostorder); - process.stdout.write(tree.id + " "); + console.log(tree.id); } function dfsInorder(tree) { @@ -32,29 +24,20 @@ function dfsInorder(tree) { return; } - 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"); + if (tree.children.length > 2) { + 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) { const stack = [tree]; while (stack.length > 0) { const current = stack.pop(); - process.stdout.write(current.id + " "); + console.log(current.id); stack.push(...current.children); } } @@ -63,26 +46,13 @@ function bfs(tree) { const queue = [tree]; while (queue.length > 0) { const current = queue.shift(); - process.stdout.write(current.id + " "); + console.log(current.id); queue.push(...current.children); } } -const root = createTree(2, 3); -console.log("[#]\nRecursive DFS:"); +const root = createTree(3, 3); dfsPreorder(root); -console.log(); -console.log("[#]\nRecursive Postorder DFS:"); dfsPostorder(root); -console.log(); -console.log("[#]\nStack-based DFS:"); dfsIterative(root); -console.log(); -console.log("[#]\nQueue-based BFS:"); bfs(root); -console.log(); -const root_binary = createTree(3, 2); -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 7382fdad0..d44345e8d 100644 --- a/contents/tree_traversal/code/julia/Tree.jl +++ b/contents/tree_traversal/code/julia/Tree.jl @@ -1,4 +1,4 @@ -using DataStructures, Printf +using DataStructures struct Node children::Vector{Node} @@ -8,7 +8,7 @@ end function DFS_recursive(n::Node) # Here we are doing something... - print(n.ID, " ") + println(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... - print(n.ID, " ") + println(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]) - print(n.ID, " ") + println(n.ID) DFS_recursive_inorder_btree(n.children[2]) elseif (length(n.children) == 1) DFS_recursive_inorder_btree(n.children[1]) - print(n.ID, " ") + println(n.ID) elseif (length(n.children) == 0) - print(n.ID, " ") + println(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) - print(top(s).ID, " ") + println(first(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) - print(first(q).ID, " ") + println(first(q).ID) temp = dequeue!(q) for child in temp.children enqueue!(q, child) @@ -84,28 +84,26 @@ function create_tree(num_row::Int64, num_child::Int64) end function main() + + println("Creating Tree") root = create_tree(2, 3) - println("[#]\nRecursive DFS:") + println("Using recursive DFS:") DFS_recursive(root); - println() - println("[#]\nRecursive Postorder DFS:") + println("Using recursive DFS with post-order traversal:") DFS_recursive_postorder(root); - println() - println("[#]\nStack-based DFS:") + println("Using stack-based DFS:") DFS_stack(root); - println() - println("[#]\nQueue-based BFS:") + println("Using queue-based BFS:") BFS_queue(root); - println() + println("Creating binary tree to test in-order traversal.") root_binary = create_tree(3,2) - println("[#]\nRecursive Inorder DFS for Binary Tree:") + println("Using In-order DFS:") DFS_recursive_inorder_btree(root_binary) - println() end main() diff --git a/contents/tree_traversal/code/php/tree_traversal.php b/contents/tree_traversal/code/php/tree_traversal.php index 3c829977b..fde55046a 100644 --- a/contents/tree_traversal/code/php/tree_traversal.php +++ b/contents/tree_traversal/code/php/tree_traversal.php @@ -40,7 +40,9 @@ class TreeTraversal { public static function DFSRecursive(Tree $tree): void { - echo $tree->getId() . ' '; + if ($tree->getId()) { + echo $tree->getId() . PHP_EOL; + } foreach ($tree->getChildren() as $child) { static::DFSRecursive($child); } @@ -51,7 +53,7 @@ public static function DFSRecursivePostorder(Tree $tree): void foreach ($tree->getChildren() as $child) { static::DFSRecursivePostorder($child); } - echo $tree->getId() . ' '; + echo $tree->getId() . PHP_EOL; } public static function DFSRecursiveInorderBinary(Tree $tree): void @@ -59,15 +61,15 @@ public static function DFSRecursiveInorderBinary(Tree $tree): void switch (count($tree->getChildren())) { case 2: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . ' '; + echo $tree->getId() . PHP_EOL; static::DFSRecursiveInorderBinary($tree->getChildren()[1]); break; case 1: static::DFSRecursiveInorderBinary($tree->getChildren()[0]); - echo $tree->getId() . ' '; + echo $tree->getId() . PHP_EOL; break; case 0: - echo $tree->getId() . ' '; + echo $tree->getId() . PHP_EOL; break; default: throw new InvalidArgumentException('Not a binary tree!'); @@ -81,7 +83,7 @@ public static function DFSStack(Tree $tree): void $temp = null; while (null !== ($temp = array_pop($stack))) { - echo $temp->getId() . ' '; + echo $temp->getId() . PHP_EOL; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -94,7 +96,7 @@ public static function DFSQueue(Tree $tree): void $temp = null; while (null !== ($temp = array_shift($stack))) { - echo $temp->getId() . ' '; + echo $temp->getId() . PHP_EOL; foreach ($temp->getChildren() as $child) { $stack[] = $child; } @@ -102,13 +104,16 @@ public static function DFSQueue(Tree $tree): void } } -function generate_tree(int $numOfRows, int $numOfChildren): Tree +function generate_tree(int $numOfRows, int $numOfChildren, int $id = -1): Tree { - $node = new Tree($numOfRows); + if ($id === -1) { + $id = 1; + } + $node = new Tree($id); - if ($numOfRows > 0) { + if ($numOfRows > 1) { for ($i = 0; $i < $numOfChildren; $i++) { - $child = generate_tree($numOfRows - 1, $numOfChildren); + $child = generate_tree($numOfRows - 1, $numOfChildren, $id * 10 + $i + 1); $node->addChild($child); } } @@ -116,28 +121,23 @@ function generate_tree(int $numOfRows, int $numOfChildren): Tree return $node; } -$node = generate_tree(2, 3); +$node = generate_tree(3, 3); -echo '[#]' . PHP_EOL . 'Recursive DFS:' . PHP_EOL; +echo 'DFS Recursive:' . PHP_EOL; TreeTraversal::DFSRecursive($node); -echo PHP_EOL; -echo '[#]' . PHP_EOL . 'Recursive Postorder DFS:' . PHP_EOL; +echo 'DFS Recursive Postorder:' . PHP_EOL; TreeTraversal::DFSRecursivePostorder($node); -echo PHP_EOL; -echo '[#]' . PHP_EOL . 'Stack-based DFS:' . PHP_EOL; +echo 'DFS Stack:' . PHP_EOL; TreeTraversal::DFSStack($node); -echo PHP_EOL; -echo '[#]' . PHP_EOL . 'Queue-based BFS:' . PHP_EOL; +echo 'DFS Queue:' . 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 '[#]' . PHP_EOL . 'Recursive Inorder DFS for Binary Tree:' . PHP_EOL; +echo 'DFS Recursive Inorder Binary:' . PHP_EOL; TreeTraversal::DFSRecursiveInorderBinary($node); -echo PHP_EOL; diff --git a/contents/tree_traversal/code/python/Tree_example.py b/contents/tree_traversal/code/python/Tree_example.py new file mode 100644 index 000000000..67dd516a3 --- /dev/null +++ b/contents/tree_traversal/code/python/Tree_example.py @@ -0,0 +1,99 @@ +class Node: + def __init__(self): + self.data = None + self.children = [] + + +def create_tree(node, num_row, num_child): + node.data = num_row + + if num_row > 0: + for i in range(num_child): + child = create_tree(Node(), num_row-1, num_child) + node.children.append(child) + + return node + + +def DFS_recursive(node): + if node.data != None: + print(node.data) + + for child in node.children: + DFS_recursive(child) + + +def DFS_recursive_postorder(node): + for child in node.children: + 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): + if (len(node.children) == 2): + DFS_recursive_inorder_btree(node.children[0]) + print(node.data) + DFS_recursive_inorder_btree(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) + else: + print("Not a binary tree!") + + +def DFS_stack(node): + stack = [] + stack.append(node) + + temp = None + + while len(stack) > 0: + print(stack[-1].data) + temp = stack.pop() + + for child in temp.children: + stack.append(child) + + +def BFS_queue(node): + queue = [] + queue.append(node) + + temp = None + + while len(queue) > 0: + print(queue[0].data) + temp = queue.pop(0) + + for child in temp.children: + queue.append(child) + + +def main(): + tree = create_tree(Node(), 3, 3) + + print("Recursive:") + DFS_recursive(tree) + + print("Recursive Postorder:") + DFS_recursive_postorder(tree) + + print("Stack:") + DFS_stack(tree) + + print("Queue:") + BFS_queue(tree) + + binaryTree = create_tree(Node(), 3, 2) + + print("Recursive Inorder Binary Tree:") + DFS_recursive_inorder_btree(binaryTree) + +if __name__ == '__main__': + main() + diff --git a/contents/tree_traversal/code/python/tree_traversal.py b/contents/tree_traversal/code/python/tree_traversal.py deleted file mode 100644 index 735837bdd..000000000 --- a/contents/tree_traversal/code/python/tree_traversal.py +++ /dev/null @@ -1,103 +0,0 @@ -class Node: - def __init__(self): - self.data = None - self.children = [] - -def create_tree(node, num_row, num_child): - node.data = num_row - - if num_row > 0: - for i in range(num_child): - child = create_tree(Node(), num_row-1, num_child) - node.children.append(child) - - return node - - -def dfs_recursive(node): - if node.data != None: - print(node.data, end=' ') - - for child in node.children: - dfs_recursive(child) - - -def dfs_recursive_postorder(node): - for child in node.children: - dfs_recursive_postorder(child) - - if node.data != None: - 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: - dfs_recursive_inorder_btree(node.children[0]) - print(node.data, end=' ') - dfs_recursive_inorder_btree(node.children[1]) - elif len(node.children) == 1: - dfs_recursive_inorder_btree(node.children[0]) - print(node.data, end=' ') - elif len(node.children) == 0: - print(node.data, end=' ') - else: - print("Not a binary tree!") - - -def dfs_stack(node): - stack = [] - stack.append(node) - - temp = None - - while len(stack) > 0: - print(stack[-1].data, end=' ') - temp = stack.pop() - - for child in temp.children: - stack.append(child) - - -def bfs_queue(node): - queue = [] - queue.append(node) - - temp = None - - while len(queue) > 0: - print(queue[0].data, end=' ') - temp = queue.pop(0) - - for child in temp.children: - queue.append(child) - - -def main(): - tree = create_tree(Node(), 2, 3) - - print("[#]\nRecursive DFS:") - dfs_recursive(tree) - print() - - print("[#]\nRecursive Postorder DFS:") - dfs_recursive_postorder(tree) - print() - - print("[#]\nStack-based DFS:") - dfs_stack(tree) - print() - - print("[#]\nQueue-based BFS:") - bfs_queue(tree) - print() - - binary_tree = create_tree(Node(), 3, 2) - - print("[#]\nRecursive Inorder DFS for Binary Tree:") - dfs_recursive_inorder_btree(binary_tree) - print() - -if __name__ == '__main__': - main() - diff --git a/contents/tree_traversal/code/rust/tree.rs b/contents/tree_traversal/code/rust/tree.rs index 60e833858..f281e1a8c 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) { - print!("{} ", n.value); + println!("{}", n.value); for child in &n.children { dfs_recursive(child); @@ -19,22 +19,22 @@ fn dfs_recursive_postorder(n: &Node) { dfs_recursive_postorder(child); } - print!("{} ", n.value); + println!("{}", n.value); } fn dfs_recursive_inorder_btree(n: &Node) { match &n.children[..] { [left, right] => { dfs_recursive_inorder_btree(left); - print!("{} ", n.value); + println!("{}", n.value); dfs_recursive_inorder_btree(right); } [left] => { dfs_recursive_inorder_btree(left); - print!("{} ", n.value); + println!("{}", n.value); } - [] => print!("{} ", n.value), - _ => print!("This is not a binary tree. "), + [] => println!("{}", n.value), + _ => println!("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() { - print!("{} ", current.value); + println!("{}", 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() { - print!("{} ", current.value); + println!("{}", current.value); queue.extend(¤t.children); } } @@ -78,24 +78,19 @@ fn create_tree(num_row: u64, num_child: u64) -> Node { fn main() { let root = create_tree(2, 3); - println!("[#]\nRecursive DFS:"); + println!("Recursive DFS:"); dfs_recursive(&root); - println!(); - println!("[#]\nRecursive Postorder DFS:"); - dfs_recursive_postorder(&root); - println!(); - - println!("[#]\nStack-based DFS:"); + println!("Stack DFS:"); dfs_stack(&root); - println!(); - println!("[#]\nQueue-based BFS:"); + println!("Queue BFS:"); bfs_queue(&root); - println!(); - println!("[#]\nRecursive Inorder DFS for Binary Tree:"); + println!("Recursive post-order DFS:"); + dfs_recursive_postorder(&root); + + println!("Recursive in-order DFS BTree:"); let root_binary = create_tree(3, 2); dfs_recursive_inorder_btree(&root_binary); - println!(); } diff --git a/contents/tree_traversal/code/smalltalk/tree_traversal.st b/contents/tree_traversal/code/smalltalk/tree_traversal.st deleted file mode 100644 index 411e5ff45..000000000 --- a/contents/tree_traversal/code/smalltalk/tree_traversal.st +++ /dev/null @@ -1,81 +0,0 @@ -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/code/swift/tree.swift b/contents/tree_traversal/code/swift/tree.swift index ae64315ec..e286c8fb0 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, terminator:" ") + print(node.value) for child in node.children! { dfsRecursive(node: child) @@ -34,19 +34,19 @@ func dfsRecursivePostOrder(node: Node) { dfsRecursivePostOrder(node: child) } - print(node.value, terminator:" ") + print(node.value) } func dfsRecursiveInOrderBinary(node: Node) { if node.children?.count == 2 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value, terminator:" ") + print(node.value) dfsRecursiveInOrderBinary(node: node.children![1]) } else if node.children?.count == 1 { dfsRecursiveInOrderBinary(node: node.children![0]) - print(node.value, terminator:" ") + print(node.value) } else if node.children?.count == 0 { - print(node.value, terminator:" ") + print(node.value) } else { print("Not a binary tree!") } @@ -58,7 +58,7 @@ func dfsStack(node: Node) { while stack.count > 0 { temp = stack.popLast()! - print(temp.value, terminator:" ") + print(temp.value) 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, terminator:" ") + print(temp.value) for child in temp.children! { queue.append(child) @@ -81,29 +81,24 @@ func bfsQueue(node: Node) { } func main() { - let root = createTree(numRows: 2, numChildren: 3) + let root = createTree(numRows: 3, numChildren: 3) - print("[#]\nRecursive DFS:") + print("Using recursive DFS:") dfsRecursive(node: root) - print() - print("[#]\nRecursive Postorder DFS:") + print("Using recursive postorder DFS:") dfsRecursivePostOrder(node: root) - print() - print("[#]\nStack-based DFS:") + print("Using stack-based DFS:") dfsStack(node: root) - print() - print("[#]\nQueue-based BFS:") + print("Using queue-based BFS:") bfsQueue(node: root) - print() let rootBinary = createTree(numRows: 3, numChildren: 2) - print("[#]\nRecursive Inorder DFS for Binary Tree:") + print("Using In-order DFS:") dfsRecursiveInOrderBinary(node: rootBinary) - print() } main() diff --git a/contents/tree_traversal/tree_traversal.md b/contents/tree_traversal/tree_traversal.md index 4b6c5b762..e03f09652 100644 --- a/contents/tree_traversal/tree_traversal.md +++ b/contents/tree_traversal/tree_traversal.md @@ -8,16 +8,16 @@ Trees are naturally recursive data structures, and because of this, we cannot ac {% sample lang="cpp" %} [import:12-15, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:6-10, lang:"csharp"](code/csharp/Tree.cs) +[import:7-11, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:7-11, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:112-128, lang:"java"](code/java/Tree.java) +[import:110-126, 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. {% sample lang="py" %} -[import:1-4, lang:"python"](code/python/tree_traversal.py) +[import:1-4, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -32,8 +32,6 @@ 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" %} @@ -56,15 +54,15 @@ Because of this, the most straightforward way to traverse the tree might be recu {% sample lang="cpp" %} [import:17-24, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:33-44, lang:"csharp"](code/csharp/Tree.cs) +[import:34-45, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:37-45, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:20-26, lang:"java"](code/java/Tree.java) +[import:21-27, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:12-19, lang:"javascript"](code/javascript/tree.js) +[import:12-15, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:17-22, lang:"python"](code/python/tree_traversal.py) +[import:18-23, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -72,15 +70,13 @@ 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:7-8, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:6-7, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:24-30, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:41-47, lang:"php"](code/php/tree_traversal.php) +[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" %} @@ -112,15 +108,15 @@ Now, in this case the first element searched through is still the root of the tr {% sample lang="cpp" %} [import:26-31, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:46-57, lang:"csharp"](code/csharp/Tree.cs) +[import:47-58, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:47-53, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:33-40, lang:"java"](code/java/Tree.java) +[import:34-41, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:21-28, lang:"javascript"](code/javascript/tree.js) +[import:17-20, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:25-30, lang:"python"](code/python/tree_traversal.py) +[import:26-31, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -128,15 +124,13 @@ 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:10-11, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:9-10, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:32-38, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:49-55, lang:"php"](code/php/tree_traversal.php) +[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" %} @@ -148,7 +142,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"](code/coconut/tree_traversal.coco) +[import:11-15, lang:="coconut"](codo/coconut/tree_traversal.coco) {% endmethod %}

@@ -163,15 +157,15 @@ In this case, the first node visited is at the bottom of the tree and moves up t {% sample lang="cpp" %} [import:34-52 lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:59-83, lang:"csharp"](code/csharp/Tree.cs) +[import:60-79, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:55-73, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:47-64, lang:"java"](code/java/Tree.java) +[import:48-62, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:30-51, lang:"javascript"](code/javascript/tree.js) +[import:22-34, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:34-45, lang:"python"](code/python/tree_traversal.py) +[import:34-46, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -179,15 +173,13 @@ 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:13-17, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:12-16, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:40-53, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:57-76, lang:"php"](code/php/tree_traversal.php) +[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" %} @@ -223,15 +215,15 @@ In code, it looks like this: {% sample lang="cpp" %} [import:55-70, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:85-98, lang:"csharp"](code/csharp/Tree.cs) +[import:81-94, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:75-93, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:67-81, lang:"java"](code/java/Tree.java) +[import:65-79, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:53-60, lang:"javascript"](code/javascript/tree.js) +[import:36-43, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:48-59, lang:"python"](code/python/tree_traversal.py) +[import:49-60, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -239,15 +231,13 @@ In code, it looks like this: {% sample lang="rs" %} [import:41-48, lang:"rust"](code/rust/tree.rs) {% sample lang="hs" %} -[import:19-23, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:18-22, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:55-67, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:78-89, lang:"php"](code/php/tree_traversal.php) +[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" %} @@ -276,15 +266,15 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can {% sample lang="cpp" %} [import:73-86, lang:"cpp"](code/c++/tree_example.cpp) {% sample lang="cs" %} -[import:100-113, lang:"csharp"](code/csharp/Tree.cs) +[import:96-109, lang:"csharp"](code/csharp/Tree.cs) {% sample lang="c" %} [import:95-113, lang:"c"](code/c/tree_traversal.c) {% sample lang="java" %} -[import:83-97, lang:"java"](code/java/Tree.java) +[import:81-95, lang:"java"](code/java/Tree.java) {% sample lang="js" %} -[import:62-69, lang:"javascript"](code/javascript/tree.js) +[import:45-52, lang:"javascript"](code/javascript/tree.js) {% sample lang="py" %} -[import:62-72, lang:"python"](code/python/tree_traversal.py) +[import:63-75, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %}

@@ -292,15 +282,13 @@ 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:25-29, lang:"haskell"](code/haskell/TreeTraversal.hs) +[import:24-28, lang:"haskell"](code/haskell/TreeTraversal.hs) {% sample lang="swift" %} [import:69-81, lang:"swift"](code/swift/tree.swift) {% sample lang="php" %} -[import:91-102, lang:"php"](code/php/tree_traversal.php) +[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" %} @@ -345,7 +333,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_traversal.py) +[import, lang:"python"](code/python/Tree_example.py) {% sample lang="scratch" %} The code snippets were taken from this [Scratch project](https://scratch.mit.edu/projects/174017753/) @@ -363,8 +351,6 @@ 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" %} diff --git a/contents/verlet_integration/code/asm-x64/verlet.s b/contents/verlet_integration/code/asm-x64/verlet.s index 87de6cb7a..0e0d031b3 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 "[#]\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" + 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 ccceb0ff3..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 << "[#]\nTime for Verlet integration is:\n" \ + std::cout << "[#] Time for Verlet integration is:\n" \ << time << std::endl; timestep timestep_sv = stormer_verlet(5.0, -10, 0.01); - std::cout << "[#]\nTime for Stormer Verlet integration is:\n" \ + std::cout << "[#] Time for Stormer Verlet integration is:\n" \ << timestep_sv.time << std::endl; - std::cout << "[#]\nVelocity for Stormer Verlet integration is:\n" \ + 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 << "[#]\nTime for velocity Verlet integration is:\n" \ + std::cout << "[#] Time for velocity Verlet integration is:\n" \ << timestep_vv.time << std::endl; - std::cout << "[#]\nVelocity for velocity Verlet integration is:\n" \ + std::cout << "[#] Velocity for velocity Verlet integration is:\n" \ << timestep_vv.vel << std::endl; return 0; diff --git a/contents/verlet_integration/code/c/SConscript b/contents/verlet_integration/code/c/SConscript deleted file mode 100644 index fd696f9ce..000000000 --- a/contents/verlet_integration/code/c/SConscript +++ /dev/null @@ -1,6 +0,0 @@ -Import('*') -from pathlib import Path - -dirname = Path.cwd().parents[1].stem - -env.C(f'#/build/c/{dirname}', Glob('*.c')) diff --git a/contents/verlet_integration/code/c/verlet.c b/contents/verlet_integration/code/c/verlet.c index a5febb92c..c42254974 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("[#]\nTime for Verlet integration is:\n"); + printf("[#] Time for Verlet integration is:\n"); printf("%lf\n", time); stormer_verlet(&time, &vel, 5.0, -10, 0.01); - printf("[#]\nTime for Stormer Verlet integration is:\n"); + printf("[#] Time for Stormer Verlet integration is:\n"); printf("%lf\n", time); - printf("[#]\nVelocity for Stormer Verlet integration is:\n"); + printf("[#] Velocity for Stormer Verlet integration is:\n"); printf("%lf\n", vel); velocity_verlet(&time, &vel, 5.0, -10, 0.01); - printf("[#]\nTime for velocity Verlet integration is:\n"); + printf("[#] Time for velocity Verlet integration is:\n"); printf("%lf\n", time); - printf("[#]\nVelocity for Stormer Verlet integration is:\n"); + 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 f8d4c6c14..f08f2a7e6 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 3fda9f950..6999df1e5 100644 --- a/contents/verlet_integration/code/fortran/verlet.f90 +++ b/contents/verlet_integration/code/fortran/verlet.f90 @@ -91,19 +91,16 @@ SUBROUTINE velocity_verlet(pos, acc, dt, time, vel) ! Verlet CALL verlet(pos, acc, dt, time) - WRITE(*,*) '[#]' - WRITE(*,*) 'Time for Verlet integration:' + WRITE(*,*) '[#] Time for Verlet integration:' WRITE(*,*) time ! stormer Verlet pos = 5d0 CALL stormer_verlet(pos, acc, dt, time, vel) - WRITE(*,*) '[#]' - WRITE(*,*) 'Time for Stormer Verlet integration:' + WRITE(*,*) '[#] Time for Stormer Verlet integration:' WRITE(*,*) time - WRITE(*,*) '[#]' - WRITE(*,*) 'Velocity for Stormer Verlet integration:' + WRITE(*,*) '[#] Velocity for Stormer Verlet integration:' WRITE(*,*) vel @@ -112,11 +109,9 @@ SUBROUTINE velocity_verlet(pos, acc, dt, time, vel) pos = 5d0 CALL velocity_verlet(pos, acc, dt, time, vel) - WRITE(*,*) '[#]' - WRITE(*,*) 'Time for velocity Verlet integration:' + WRITE(*,*) '[#] Time for velocity Verlet integration:' WRITE(*,*) time - WRITE(*,*) '[#]' - WRITE(*,*) 'Velocity for velocity Verlet integration:' + 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 d4fc956a9..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("[#]\nTime for Verlet integration is:") + fmt.Println("[#] Time for Verlet integration is:") fmt.Println(time) time, vel := stormerVerlet(5., -10., .01) - fmt.Println("[#]\nTime for Stormer Verlet integration is:") + fmt.Println("[#] Time for Stormer Verlet integration is:") fmt.Println(time) - fmt.Println("[#]\nVelocity for Stormer Verlet integration is:") + fmt.Println("[#] Velocity for Stormer Verlet integration is:") fmt.Println(vel) time, vel = velocityVerlet(5., -10., .01) - fmt.Println("[#]\nTime for velocity Verlet integration is:") + fmt.Println("[#] Time for velocity Verlet integration is:") fmt.Println(time) - fmt.Println("[#]\nVelocity for velocity Verlet integration is:") + 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 af964d4d7..675c7f39b 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 "[#]\nTime for Verlet integration is:" + putStrLn "[#] Time for Verlet integration is:" putStrLn $ fst $ timeVelocity verlet - putStrLn "[#]\nTime for Stormer Verlet integration is:" + putStrLn "[#] Time for Stormer Verlet integration is:" putStrLn $ fst $ timeVelocity stormerVerlet - putStrLn "[#]\nVelocity for Stormer Verlet integration is:" + putStrLn "[#] Velocity for Stormer Verlet integration is:" putStrLn $ snd $ timeVelocity stormerVerlet - putStrLn "[#]\nTime for velocity Verlet integration is:" + putStrLn "[#] Time for velocity Verlet integration is:" putStrLn $ fst $ timeVelocity velocityVerlet - putStrLn "[#]\nVelocity for velocity Verlet integration is:" + 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 38283abed..35387cf8b 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("[#]\nTime for Verlet integration is:"); + System.out.println("[#] Time for Verlet integration is:"); System.out.println(verletTime); VerletValues stormerVerlet = stormer_verlet(5.0, -10, 0.01); - System.out.println("[#]\nTime for Stormer Verlet integration is:"); + System.out.println("[#] Time for Stormer Verlet integration is:"); System.out.println(stormerVerlet.time); - System.out.println("[#]\nVelocity for Stormer Verlet integration is:"); + 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("[#]\nTime for velocity Verlet integration is:"); + System.out.println("[#] Time for velocity Verlet integration is:"); System.out.println(velocityVerlet.time); - System.out.println("[#]\nVelocity for velocity Verlet integration is:"); + 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 d406482d4..7ea09e187 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(`[#]\nTime for Verlet integration is:`); +console.log(`[#] Time for Verlet integration is:`); console.log(`${time}`); const stormer = stormerVerlet(5, -10, 0.01); -console.log(`[#]\nTime for Stormer Verlet integration is:`); +console.log(`[#] Time for Stormer Verlet integration is:`); console.log(`${stormer.time}`); -console.log(`[#]\nVelocity for Stormer Verlet integration is:`); +console.log(`[#] Velocity for Stormer Verlet integration is:`); console.log(`${stormer.vel}`); const velocity = velocityVerlet(5, -10, 0.01); -console.log(`[#]\nTime for velocity Verlet integration is:`); +console.log(`[#] Time for velocity Verlet integration is:`); console.log(`${velocity.time}`); -console.log(`[#]\nVelocity for velocity Verlet integration is:`); +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 2d50e5512..b9edcea98 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("[#]\nTime for Verlet integration is:") + println("[#] Time for Verlet integration is:") println("$(time)") time, vel = stormer_verlet(5.0, -10.0, 0.01); - println("[#]\nTime for Stormer Verlet integration is:") + println("[#] Time for Stormer Verlet integration is:") println("$(time)") - println("[#]\nVelocity for Stormer Verlet integration is:") + println("[#] Velocity for Stormer Verlet integration is:") println("$(vel)") time, vel = velocity_verlet(5.0, -10.0, 0.01); - println("[#]\nTime for velocity Verlet integration is:") + println("[#] Time for velocity Verlet integration is:") println("$(time)") - println("[#]\nVelocity for velocity Verlet integration is:") + println("[#] Velocity 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 3b365451c..79bee7b6a 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("[#]\nTime for Verlet integration is:") + println("[#] Time for Verlet integration is:") println("$verletTime") val stormerVerlet = stormerVerlet(5.0, -10.0, 0.01) - println("[#]\nTime for Stormer Verlet integration is:") + println("[#] Time for Stormer Verlet integration is:") println("${stormerVerlet.time}") - println("[#]\nVelocity for Stormer Verlet integration is:") + println("[#] Velocity for Stormer Verlet integration is:") println("${stormerVerlet.vel}") val velocityVerlet = velocityVerlet(5.0, -10.0, 0.01) - println("[#]\nTime for Velocity Verlet integration is:") + println("[#] Time for Velocity Verlet integration is:") println("${velocityVerlet.time}") - println("[#]\nVelocity for Velocity Verlet integration is:") + 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 ff454b7ee..2e92b57c4 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 "[#]\nTime for Verlet integration is:" + echo "[#] Time for Verlet integration is:" echo timeV let (timeSV, velSV) = stormerVerlet(5.0, -10.0, 0.01) - echo "[#]\nTime for Stormer Verlet integration is:" + echo "[#] Time for Stormer Verlet integration is:" echo timeSV - echo "[#]\nVelocity for Stormer Verlet integration is:" + echo "[#] Velocity for Stormer Verlet integration is:" echo velSV let (timeVV, velVV) = velocityVerlet(5.0, -10.0, 0.01) - echo "[#]\nTime for velocity Verlet integration is:" + echo "[#] Time for velocity Verlet integration is:" echo timeVV - echo "[#]\nVelocity for velocity Verlet integration is:" + 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 063e19666..18dc627d3 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("[#]\nTime for Verlet integration is:") + print("[#] Time for Verlet integration is:") print("{:.10f}".format(time)) time, vel = stormer_verlet(5, -10, 0.01) - print("[#]\nTime for Stormer Verlet integration is:") + print("[#] Time for Stormer Verlet integration is:") print("{:.10f}".format(time)) - print("[#]\nVelocity for Stormer Verlet integration is:") + print("[#] Velocity for Stormer Verlet integration is:") print("{:.10f}".format(vel)) time, vel = velocity_verlet(5, -10, 0.01) - print("[#]\nTime for velocity Verlet integration is:") + print("[#] Time for velocity Verlet integration is:") print("{:.10f}".format(time)) - print("[#]\nVelocity for velocity Verlet integration is:") + print("[#] Velocity 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 d11243568..4a6c38a48 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 "[#]\nTime for Verlet integration is:" +puts "[#] Time for Verlet integration is:" p verlet(5.0, -10, 0.01) time, vel = stormer_verlet(5.0, -10, 0.01) -puts "[#]\nTime for Stormer Verlet integration is:" +puts "[#] Time for Stormer Verlet integration is:" p time -puts "[#]\nVelocity for Stormer Verlet integration is:" +puts "[#] Velocity for Stormer Verlet integration is:" p vel time, vel = velocity_verlet(5.0, -10, 0.01) -puts "[#]\nTime for velocity Verlet integration is:" +puts "[#] Time for velocity Verlet integration is:" p time -puts "[#]\nVelocity for velocity Verlet integration is:" +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 8901a3790..f765da864 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!("[#]\nTime for Verlet integration is:"); + println!("[#] Time for Verlet integration is:"); println!("{}", time_v); - println!("[#]\nTime for Stormer Verlet integration is:"); + println!("[#] Time for Stormer Verlet integration is:"); println!("{}", time_sv); - println!("[#]\nVelocity for Stormer Verlet integration is:"); + println!("[#] Velocity for Stormer Verlet integration is:"); println!("{}", vel_sv); - println!("[#]\nTime for velocity Verlet integration is:"); + println!("[#] Time for velocity Verlet integration is:"); println!("{}", time_vv); - println!("[#]\nVelocity for velocity Verlet integration is:"); + 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 f7d1973bc..7991a0082 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("[#]\nTime for Verlet integration is:") + print("[#] Time for Verlet integration is:") print("\(verletTime)") let stormer = stormerVerlet(pos: 5.0, acc: -10.0, dt: 0.01); - print("[#]\nTime for Stormer Verlet integration is:") + print("[#] Time for Stormer Verlet integration is:") print("\(stormer.time)") - print("[#]\nVelocity for Stormer Verlet integration is:") + print("[#] Velocity for Stormer Verlet integration is:") print("\(stormer.vel)") let velVerlet = velocityVerlet(pos: 5.0, acc: -10, dt: 0.01) - print("[#]\nTime for velocity Verlet integration is:") + print("[#] Time for velocity Verlet integration is:") print("\(velVerlet.time)") - print("[#]\nVelocity for velocity Verlet integration is:") + print("[#] Velocity for velocity Verlet integration is:") print("\(velVerlet.vel)") } diff --git a/contents/verlet_integration/verlet_integration.md b/contents/verlet_integration/verlet_integration.md index 08fe4a4b3..402a7ba1b 100644 --- a/contents/verlet_integration/verlet_integration.md +++ b/contents/verlet_integration/verlet_integration.md @@ -42,6 +42,15 @@ Here is what it looks like in code: [import:1-10, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:14-21, lang:"haskell"](code/haskell/verlet.hs) +{% sample lang="scratch" %} +Unfortunately, this has not yet been implemented in scratch, so here's Julia code: +[import:1-13, lang:"julia"](code/julia/verlet.jl) +{% sample lang="m" %} +Unfortunately, this has not yet been implemented in matlab, so here's Julia code: +[import:1-13, lang:"julia"](code/julia/verlet.jl) +{% sample lang="LabVIEW" %} +Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: +[import:1-13, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:1-14, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -91,6 +100,15 @@ However, the error for this is $$\mathcal{O}(\Delta t)$$, which is quite poor, b [import:12-23, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:23-28, lang:"haskell"](code/haskell/verlet.hs) +{% sample lang="scratch" %} +Unfortunately, this has not yet been implemented in scratch, so here's Julia code: +[import:15-31, lang:"julia"](code/julia/verlet.jl) +{% sample lang="m" %} +Unfortunately, this has not yet been implemented in matlab, so here's Julia code: +[import:15-31, lang:"julia"](code/julia/verlet.jl) +{% sample lang="LabVIEW" %} +Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: +[import:15-31, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:16-32, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -154,6 +172,15 @@ Here is the velocity Verlet method in code: [import:25-34, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import:30-35, lang:"haskell"](code/haskell/verlet.hs) +{% sample lang="scratch" %} +Unfortunately, this has not yet been implemented in scratch, so here's Julia code: +[import:33-45, lang:"julia"](code/julia/verlet.jl) +{% sample lang="m" %} +Unfortunately, this has not yet been implemented in matlab, so here's Julia code: +[import:33-45, lang:"julia"](code/julia/verlet.jl) +{% sample lang="LabVIEW" %} +Unfortunately, this has not yet been implemented in LabVIEW, so here's Julia code: +[import:33-45, lang:"julia"](code/julia/verlet.jl) {% sample lang="js" %} [import:34-45, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} @@ -203,6 +230,19 @@ Both of these methods work simply by iterating timestep-by-timestep and can be w [import, lang:"python"](code/python/verlet.py) {% sample lang="hs" %} [import, lang:"haskell"](code/haskell/verlet.hs) +{% sample lang="scratch" %} +Submitted by Jie +

+ +

+Link: [https://scratch.mit.edu/projects/173039394/](https://scratch.mit.edu/projects/173039394/) +{% sample lang="m" %} +[import, lang:"matlab"](code/matlab/verlet.m) +{% sample lang="LabVIEW" %} +Submitted by P. Mekhail +

+ +

{% sample lang="js" %} [import, lang:"javascript"](code/javascript/verlet.js) {% sample lang="rs" %} From 0d871225223c018004d1ed2ed4413b91a03c85b6 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Wed, 1 Dec 2021 03:13:56 +0100 Subject: [PATCH 25/30] Standardize OCaml output I don't know that much about OCaml, so I'm not sure how idomatic this is. --- contents/euclidean_algorithm/code/ocaml/euclidean_example.ml | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/ocaml/euclidean_example.ml b/contents/euclidean_algorithm/code/ocaml/euclidean_example.ml index 27e3ab166..c363e5e4f 100644 --- a/contents/euclidean_algorithm/code/ocaml/euclidean_example.ml +++ b/contents/euclidean_algorithm/code/ocaml/euclidean_example.ml @@ -19,6 +19,7 @@ let euclid_sub a b = let chk1 = euclid_mod (64 * 67) (64 * 81) let chk2 = euclid_sub (128 * 12) (128 * 77) let () = + Printf.printf "[#]\nModulus-based euclidean algorithm result:\n"; chk1 |> print_int |> print_newline; - chk2 |> print_int |> print_newline - + Printf.printf "[#]\nSubtraction-based euclidean algorithm result:\n"; + chk2 |> print_int |> print_newline \ No newline at end of file From 0de4c6c90105d091339a5d0ac7cb06fbb50dfeca Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Wed, 1 Dec 2021 03:18:21 +0100 Subject: [PATCH 26/30] Standardize asm-x64 output --- .../euclidean_algorithm/code/asm-x64/euclidean_example.s | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/contents/euclidean_algorithm/code/asm-x64/euclidean_example.s b/contents/euclidean_algorithm/code/asm-x64/euclidean_example.s index c08bb0878..53a008908 100644 --- a/contents/euclidean_algorithm/code/asm-x64/euclidean_example.s +++ b/contents/euclidean_algorithm/code/asm-x64/euclidean_example.s @@ -1,7 +1,8 @@ .intel_syntax noprefix .section .rodata - fmt: .string "%d\n" + euclid_mod_fmt: .string "[#]\nModulus-based euclidean algorithm result:\n%d\n" + euclid_sub_fmt: .string "[#]\nSubtraction-based euclidean algorithm result:\n%d\n" .section .text .global main @@ -59,14 +60,14 @@ main: mov rdi, 4288 # Call euclid_mod mov rsi, 5184 call euclid_mod - mov rdi, OFFSET fmt # Print output + mov rdi, OFFSET euclid_mod_fmt # Print output mov rsi, rax xor rax, rax call printf mov rdi, 1536 # Call euclid_sub mov rsi, 9856 call euclid_sub - mov rdi, OFFSET fmt # Print output + mov rdi, OFFSET euclid_sub_fmt # Print output mov rsi, rax xor rax, rax call printf From ab4f8c2f56abafc80f855202abc7d1071fff2452 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Wed, 1 Dec 2021 03:22:38 +0100 Subject: [PATCH 27/30] Standardize coconut output --- contents/euclidean_algorithm/code/coconut/euclidean.coco | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/contents/euclidean_algorithm/code/coconut/euclidean.coco b/contents/euclidean_algorithm/code/coconut/euclidean.coco index abb649193..08cb851a1 100644 --- a/contents/euclidean_algorithm/code/coconut/euclidean.coco +++ b/contents/euclidean_algorithm/code/coconut/euclidean.coco @@ -15,5 +15,7 @@ addpattern def euclid_mod(0, b is int) = b addpattern def euclid_mod(a is int, b is int) = euclid_mod(b, a % b) if __name__ == '__main__': - print('[#]\nModulus-based euclidean algorithm result:\n', euclid_mod(64 * 67, 64 * 81)) - print('[#]\nSubtraction-based euclidean algorithm result:\n', euclid_sub(128 * 12, 128 * 77)) + print('[#]\nModulus-based euclidean algorithm result:') + print(euclid_mod(64 * 67, 64 * 81)) + print('[#]\nSubtraction-based euclidean algorithm result:') + print(euclid_sub(128 * 12, 128 * 77)) From 19033a95572b1cf3a624cd93044ecdbab0e06489 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Wed, 1 Dec 2021 03:31:06 +0100 Subject: [PATCH 28/30] Standardize racket output --- .../euclidean_algorithm/code/racket/euclidean_algorithm.rkt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/contents/euclidean_algorithm/code/racket/euclidean_algorithm.rkt b/contents/euclidean_algorithm/code/racket/euclidean_algorithm.rkt index f170d8e17..8d19eab86 100755 --- a/contents/euclidean_algorithm/code/racket/euclidean_algorithm.rkt +++ b/contents/euclidean_algorithm/code/racket/euclidean_algorithm.rkt @@ -23,5 +23,7 @@ ) ) +(displayln "[#]\nModulus-based euclidean algorithm result:") (displayln (euclid_sub (* 64 67) (* 64 81))) +(displayln "[#]\nSubtraction-based euclidean algorithm result:") (displayln (euclid_mod (* 128 12) (* 128 77))) From a7e318da47f2b58384b9fe0a029e97f6c4781de4 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Wed, 1 Dec 2021 03:33:25 +0100 Subject: [PATCH 29/30] Standardize scheme output --- contents/euclidean_algorithm/code/scheme/euclidalg.ss | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contents/euclidean_algorithm/code/scheme/euclidalg.ss b/contents/euclidean_algorithm/code/scheme/euclidalg.ss index 3d891ba73..b781c7c7d 100644 --- a/contents/euclidean_algorithm/code/scheme/euclidalg.ss +++ b/contents/euclidean_algorithm/code/scheme/euclidalg.ss @@ -11,5 +11,7 @@ a (euclid-mod b (modulo a b)))) +(display "[#]\nModulus-based euclidean algorithm result:") (newline) (display (euclid-mod (* 64 67) (* 64 81))) (newline) -(display (euclid-sub (* 64 12) (* 64 27))) (newline) +(display "[#]\nSubtraction-based euclidean algorithm result:") (newline) +(display (euclid-sub (* 128 12) (* 128 77))) (newline) From 90b6858e33808179282fc13ddbd1b1030b564e32 Mon Sep 17 00:00:00 2001 From: stormofice <58337328+stormofice@users.noreply.github.com> Date: Thu, 2 Dec 2021 16:45:48 +0100 Subject: [PATCH 30/30] Update contents/euclidean_algorithm/code/fortran/euclidean.f90 Co-authored-by: James Schloss --- contents/euclidean_algorithm/code/fortran/euclidean.f90 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contents/euclidean_algorithm/code/fortran/euclidean.f90 b/contents/euclidean_algorithm/code/fortran/euclidean.f90 index 086d2fee2..e0dc9610e 100644 --- a/contents/euclidean_algorithm/code/fortran/euclidean.f90 +++ b/contents/euclidean_algorithm/code/fortran/euclidean.f90 @@ -49,7 +49,7 @@ PROGRAM euclidean b = 128 * 77 WRITE(*,'(a)') '[#]' - WRITE(*,'(a)') 'Subtraction-based euclidean algorithm result::' + WRITE(*,'(a)') 'Subtraction-based euclidean algorithm result:' WRITE(*, '(g0)') euclid_sub(a, b) END PROGRAM euclidean