├── .clang-format ├── .devcontainer └── devcontainer.json ├── .editorconfig ├── .gitattributes ├── .github ├── FUNDING.yml ├── ISSUE_TEMPLATE │ ├── BUG_REPORT.md │ ├── CHAPTER_REQUEST.md │ └── FEATURE_REQUEST.md ├── PULL_REQUEST_TEMPLATE │ ├── CHAPTER_SUBMISSION_TEMPLATE.md │ └── CODE_SUBMISSION_TEMPLATE.md └── workflows │ ├── build.yml │ ├── deploy.yml │ ├── issue_comment.yml │ └── publish_container.yml ├── .gitignore ├── .nojekyll ├── CODE_OF_CONDUCT.md ├── CONTRIBUTING.md ├── CONTRIBUTORS.md ├── Dockerfile ├── LICENSE.md ├── README.md ├── SConstruct ├── SUMMARY.md ├── book.json ├── contents ├── IFS │ ├── IFS.md │ ├── code │ │ ├── c │ │ │ └── IFS.c │ │ ├── clisp │ │ │ └── ifs.lisp │ │ ├── coconut │ │ │ └── IFS.coco │ │ ├── cpp │ │ │ └── IFS.cpp │ │ ├── haskell │ │ │ └── IFS.hs │ │ ├── java │ │ │ └── IFS.java │ │ ├── julia │ │ │ └── IFS.jl │ │ ├── powershell │ │ │ └── IFS.ps1 │ │ └── python │ │ │ └── IFS.py │ └── res │ │ ├── IFS_square_1.png │ │ ├── IFS_square_2.png │ │ ├── IFS_square_3.png │ │ ├── IFS_square_vid_1.mp4 │ │ ├── IFS_triangle_1.png │ │ ├── IFS_triangle_2.png │ │ ├── IFS_triangle_3.png │ │ ├── IFS_triangle_4.png │ │ ├── IFS_triangle_5.png │ │ ├── IFS_triangle_vid_1.mp4 │ │ ├── IFS_triangle_vid_2.mp4 │ │ ├── chaos_1.png │ │ ├── chaos_2.png │ │ ├── chaos_vid_1.mp4 │ │ └── chaos_vid_2.mp4 ├── affine_transformations │ ├── affine_transformations.md │ └── res │ │ ├── a11_cube_white.mp4 │ │ ├── a11_square_white.mp4 │ │ ├── a12_cube_white.mp4 │ │ ├── a12_square_white.mp4 │ │ ├── a13_cube_white.mp4 │ │ ├── a13_square_white.mp4 │ │ ├── a21_cube_white.mp4 │ │ ├── a21_square_white.mp4 │ │ ├── a22_cube_white.mp4 │ │ ├── a22_square_white.mp4 │ │ ├── a23_cube_white.mp4 │ │ ├── a23_square_white.mp4 │ │ ├── a31_cube_white.mp4 │ │ ├── a32_cube_white.mp4 │ │ ├── a33_cube_white.mp4 │ │ ├── cosines_white.mp4 │ │ ├── rotation_cube_white.mp4 │ │ ├── rotation_square_white.mp4 │ │ ├── semi_rotate_white.mp4 │ │ └── sines_white.mp4 ├── approximate_counting │ ├── approximate_counting.md │ ├── code │ │ ├── c │ │ │ ├── SConscript │ │ │ └── approximate_counting.c │ │ ├── cpp │ │ │ └── approximate_counting.cpp │ │ ├── java │ │ │ └── ApproximateCounting.java │ │ ├── julia │ │ │ └── approximate_counting.jl │ │ └── python │ │ │ └── approximate_counting.py │ └── res │ │ ├── a_change.png │ │ ├── approximations.png │ │ ├── approximationsexp.png │ │ ├── counting.jl │ │ ├── deltas.png │ │ ├── hands.png │ │ ├── hist_1.png │ │ ├── hist_2.png │ │ ├── hist_2_plot.gp │ │ ├── hist_3.png │ │ ├── hist_plot.gp │ │ ├── histexp_1.png │ │ ├── histexp_2.png │ │ ├── histexp_3.png │ │ ├── histograms.png │ │ ├── plot.gp │ │ ├── plot_a.gp │ │ └── plot_deltas.gp ├── backward_euler_method │ └── backward_euler_method.md ├── barnes_hut_algorithm │ └── barnes_hut_algorithm.md ├── barnsley │ ├── barnsley.md │ ├── code │ │ ├── c │ │ │ └── barnsley.c │ │ ├── coconut │ │ │ └── barnsley.coco │ │ ├── cpp │ │ │ └── barnsley.cpp │ │ ├── haskell │ │ │ └── Barnsley.hs │ │ ├── java │ │ │ └── Barnsley.java │ │ ├── julia │ │ │ └── barnsley.jl │ │ └── rust │ │ │ ├── Cargo.toml │ │ │ └── barnsley.rs │ └── res │ │ ├── affine_fern_0.mp4 │ │ ├── affine_fern_1.mp4 │ │ ├── affine_fern_2.mp4 │ │ ├── affine_fern_3.mp4 │ │ ├── affine_rnd_0.mp4 │ │ ├── affine_rnd_1.mp4 │ │ ├── affine_rnd_2.mp4 │ │ ├── affine_rnd_3.mp4 │ │ ├── fern_twiddle_0.mp4 │ │ ├── fern_twiddle_1.mp4 │ │ ├── fern_twiddle_2.mp4 │ │ ├── fern_twiddle_3.mp4 │ │ └── full_fern.png ├── bitlogic │ ├── bitlogic.md │ └── res │ │ ├── and.jpg │ │ ├── nand.jpg │ │ ├── nor.jpg │ │ ├── not.jpg │ │ ├── or.jpg │ │ └── xor.jpg ├── cc │ ├── CC-BY-SA_icon.svg │ ├── README.txt │ └── license.txt ├── chans_algorithm │ └── chans_algorithm.md ├── choosing_a_language │ └── choosing_a_language.md ├── code_reviews │ └── code_reviewers.md ├── compiled_languages │ └── compiled_languages.md ├── computational_geometry │ └── computational_geometry.md ├── computer_graphics │ └── computer_graphics.md ├── computus │ ├── code │ │ ├── c │ │ │ └── gauss_easter.c │ │ ├── clisp │ │ │ └── gauss-easter.lisp │ │ ├── cpp │ │ │ └── gauss_easter.cpp │ │ ├── crystal │ │ │ └── gauss_easter.cr │ │ ├── dart │ │ │ └── gauss_easter.dart │ │ ├── haskell │ │ │ └── gauss_easter.hs │ │ ├── javascript │ │ │ └── gauss_easter.js │ │ ├── julia │ │ │ └── gauss_easter.jl │ │ ├── nim │ │ │ └── gauss_easter.nim │ │ ├── powershell │ │ │ └── gauss_easter.ps1 │ │ ├── python │ │ │ └── gauss_easter.py │ │ ├── rust │ │ │ └── gauss_easter.rs │ │ ├── scala │ │ │ └── gauss_easter.scala │ │ └── typescript │ │ │ └── gauss_easter.ts │ ├── computus.md │ └── res │ │ ├── metonic.png │ │ ├── orbit.png │ │ ├── orbit.svg │ │ ├── servois_1800.png │ │ ├── servois_2000.png │ │ └── synodic_half_year.png ├── convolutions │ ├── 1d │ │ ├── 1d.md │ │ └── code │ │ │ ├── csharp │ │ │ └── 1DConvolution.cs │ │ │ ├── julia │ │ │ └── 1d_convolution.jl │ │ │ └── python │ │ │ └── 1d_convolution.py │ ├── 2d │ │ ├── 2d.md │ │ └── code │ │ │ ├── julia │ │ │ └── 2d_convolution.jl │ │ │ └── python │ │ │ └── 2d_convolution.py │ ├── convolutional_theorem │ │ ├── code │ │ │ ├── julia │ │ │ │ └── convolutional_theorem.jl │ │ │ └── python │ │ │ │ └── convolutional_theorem.py │ │ └── convolutional_theorem.md │ ├── convolutions.md │ ├── multiplication │ │ └── multiplication.md │ └── res │ │ ├── 1d_gaussian.mp4 │ │ ├── 1d_rand_gaussian_cyclic.mp4 │ │ ├── 1d_rand_gaussian_full.mp4 │ │ ├── 1d_rand_gaussian_simple.mp4 │ │ ├── 1d_sawtooth.mp4 │ │ ├── 2d.mp4 │ │ ├── circle_blur.png │ │ ├── cyclic.png │ │ ├── double_gaussian.mp4 │ │ ├── full_linear.png │ │ ├── heart_8bit.png │ │ ├── sawtooth.png │ │ ├── simple_linear.png │ │ ├── sobel_filters.png │ │ ├── square_wave.png │ │ ├── triangle_square_conv.mp4 │ │ └── triangle_wave.png ├── cooley_tukey │ ├── code │ │ ├── asm-x64 │ │ │ ├── SConscript │ │ │ └── fft.s │ │ ├── c │ │ │ ├── SConscript │ │ │ └── fft.c │ │ ├── clisp │ │ │ └── fft.lisp │ │ ├── clojure │ │ │ └── fft.clj │ │ ├── cpp │ │ │ └── fft.cpp │ │ ├── haskell │ │ │ └── fft.hs │ │ ├── javascript │ │ │ └── fft.js │ │ ├── julia │ │ │ └── fft.jl │ │ ├── python │ │ │ └── fft.py │ │ └── rust │ │ │ ├── Cargo.toml │ │ │ └── fft.rs │ ├── cooley_tukey.md │ └── res │ │ ├── FT_example.png │ │ ├── butterfly_diagram.png │ │ ├── fft.png │ │ ├── out.dat │ │ ├── radix-2screen.jpg │ │ ├── radix-2screen_positive.jpg │ │ ├── radix-8screen.jpg │ │ └── sinusoid.png ├── data_compression │ └── data_compression.md ├── data_structures │ └── data_structures.md ├── decision_problems │ └── decision_problems.md ├── differential_equations │ └── differential_equations.md ├── domain_coloring │ ├── code │ │ ├── gnuplot │ │ │ └── domain_coloring.gp │ │ └── python │ │ │ └── domain_coloring.py │ ├── domain_coloring.md │ └── res │ │ ├── absz.png │ │ ├── hsv.png │ │ ├── hsv2.png │ │ ├── hsv3.png │ │ ├── hsv4.png │ │ ├── hsv5.png │ │ ├── rgb1.png │ │ ├── rgb2.png │ │ ├── shade.png │ │ └── z2.png ├── euclidean_algorithm │ ├── code │ │ ├── asm-x64 │ │ │ └── euclidean_example.s │ │ ├── bash │ │ │ └── euclid.bash │ │ ├── c │ │ │ └── euclidean_example.c │ │ ├── clisp │ │ │ └── euclidean.lisp │ │ ├── clojure │ │ │ └── euclidean_example.clj │ │ ├── coconut │ │ │ └── euclidean.coco │ │ ├── cpp │ │ │ └── euclidean.cpp │ │ ├── csharp │ │ │ ├── EuclideanAlgorithm.cs │ │ │ └── Program.cs │ │ ├── d │ │ │ └── euclidean_algorithm.d │ │ ├── emojicode │ │ │ └── euclidean_algorithm.emojic │ │ ├── factor │ │ │ └── euclid.factor │ │ ├── fortran │ │ │ ├── SConscript │ │ │ ├── euclidean.f90 │ │ │ └── interactive_euclidean.f90 │ │ ├── go │ │ │ └── euclidean.go │ │ ├── haskell │ │ │ └── euclidean_algorithm.hs │ │ ├── java │ │ │ └── EuclideanAlgo.java │ │ ├── javascript │ │ │ └── euclidean_example.js │ │ ├── julia │ │ │ └── euclidean.jl │ │ ├── kotlin │ │ │ └── Euclidean.kt │ │ ├── lolcode │ │ │ └── euclid.lol │ │ ├── lua │ │ │ └── euclidean.lua │ │ ├── matlab │ │ │ └── euclidean.m │ │ ├── nim │ │ │ └── euclid_algorithm.nim │ │ ├── ocaml │ │ │ └── euclidean_example.ml │ │ ├── php │ │ │ └── euclidean.php │ │ ├── piet │ │ │ ├── euclidian_algorithm.piet │ │ │ ├── mod │ │ │ │ ├── euclidian_algorithm_mod.png │ │ │ │ └── euclidian_algorithm_mod_large.png │ │ │ └── subtract │ │ │ │ ├── euclidian_algorithm_subtract.png │ │ │ │ └── euclidian_algorithm_subtract_large.png │ │ ├── powershell │ │ │ └── euclidean_algorithm.ps1 │ │ ├── python │ │ │ └── euclidean_example.py │ │ ├── racket │ │ │ └── euclidean_algorithm.rkt │ │ ├── ruby │ │ │ └── euclidean.rb │ │ ├── rust │ │ │ └── euclidean_example.rs │ │ ├── scala │ │ │ └── euclidean.scala │ │ ├── scheme │ │ │ └── euclidalg.ss │ │ ├── scratch │ │ │ ├── euclid_mod.svg │ │ │ ├── euclid_sub.svg │ │ │ ├── euclidean.txt │ │ │ └── main.svg │ │ ├── smalltalk │ │ │ └── euclid.st │ │ ├── swift │ │ │ └── euclidean_algorithm.swift │ │ ├── viml │ │ │ └── euclidean.vim │ │ └── whitespace │ │ │ ├── euclidian_mod.ws │ │ │ ├── euclidian_mod_comments.ws │ │ │ ├── euclidian_sub.ws │ │ │ └── euclidian_sub_comments.ws │ ├── euclidean_algorithm.md │ └── res │ │ ├── modulus.png │ │ └── subtraction.png ├── flood_fill │ ├── code │ │ ├── c │ │ │ └── flood_fill.c │ │ ├── coconut │ │ │ └── flood_fill.coco │ │ ├── cpp │ │ │ └── flood_fill.cpp │ │ ├── julia │ │ │ └── flood_fill.jl │ │ └── python │ │ │ └── flood_fill.py │ ├── flood_fill.md │ └── res │ │ ├── example.png │ │ ├── flood_fill.svg │ │ ├── grid_1.png │ │ ├── grid_2.png │ │ ├── grid_3.png │ │ ├── grid_4.png │ │ ├── grid_5.png │ │ ├── grid_6.png │ │ ├── queue_animation.mp4 │ │ ├── recurse_animation.mp4 │ │ └── simple_circle.png ├── fortran │ └── fortran.md ├── forward_euler_method │ ├── code │ │ ├── asm-x64 │ │ │ ├── SConscript │ │ │ └── euler.s │ │ ├── c │ │ │ ├── SConscript │ │ │ └── euler.c │ │ ├── clisp │ │ │ └── euler.lisp │ │ ├── cpp │ │ │ └── euler.cpp │ │ ├── elm │ │ │ ├── elm.json │ │ │ └── src │ │ │ │ └── Euler.elm │ │ ├── fortran │ │ │ └── euler.f90 │ │ ├── go │ │ │ └── euler.go │ │ ├── haskell │ │ │ └── euler.hs │ │ ├── java │ │ │ └── ForwardEuler.java │ │ ├── javascript │ │ │ └── euler.js │ │ ├── julia │ │ │ └── euler.jl │ │ ├── matlab │ │ │ └── euler.m │ │ ├── nim │ │ │ └── forwardeuler.nim │ │ ├── python │ │ │ └── euler.py │ │ ├── rust │ │ │ └── euler.rs │ │ ├── swift │ │ │ └── euler.swift │ │ └── v │ │ │ └── euler.v │ ├── forward_euler_method.md │ └── res │ │ ├── error.png │ │ └── instability.png ├── gaussian_elimination │ ├── code │ │ ├── c │ │ │ └── gaussian_elimination.c │ │ ├── cpp │ │ │ └── gaussian_elimination.cpp │ │ ├── go │ │ │ └── gaussian_elimination.go │ │ ├── haskell │ │ │ └── gaussianElimination.hs │ │ ├── java │ │ │ └── GaussianElimination.java │ │ ├── javascript │ │ │ └── gaussian_elimination.js │ │ ├── julia │ │ │ └── gaussian_elimination.jl │ │ ├── python │ │ │ └── gaussian_elimination.py │ │ └── rust │ │ │ └── gaussian_elimination.rs │ ├── gaussian_elimination.md │ └── res │ │ └── GE_vis.mp4 ├── gift_wrapping │ └── gift_wrapping.md ├── graham_scan │ ├── code │ │ ├── c │ │ │ ├── SConscript │ │ │ └── graham.c │ │ ├── clisp │ │ │ └── graham-scan.lisp │ │ ├── coconut │ │ │ └── graham_scan.coco │ │ ├── cpp │ │ │ └── graham_scan.cpp │ │ ├── go │ │ │ └── graham.go │ │ ├── haskell │ │ │ └── grahamScan.hs │ │ ├── java │ │ │ └── GrahamScan.java │ │ ├── javascript │ │ │ └── graham-scan.js │ │ ├── julia │ │ │ └── graham.jl │ │ └── python │ │ │ └── graham_scan.py │ └── graham_scan.md ├── how_to_contribute │ ├── how_to_contribute.md │ └── res │ │ └── codeblock.txt ├── huffman_encoding │ ├── code │ │ ├── asm-x64 │ │ │ └── huffman.s │ │ ├── c │ │ │ └── huffman.c │ │ ├── clojure │ │ │ └── huffman.clj │ │ ├── coconut │ │ │ └── huffman.coco │ │ ├── cpp │ │ │ └── huffman.cpp │ │ ├── csharp │ │ │ ├── HuffmanCoding.cs │ │ │ └── Program.cs │ │ ├── go │ │ │ └── huffman.go │ │ ├── haskell │ │ │ └── huffman.hs │ │ ├── java │ │ │ └── huffman.java │ │ ├── javascript │ │ │ └── huffman.js │ │ ├── julia │ │ │ └── huffman.jl │ │ ├── lua │ │ │ └── huffman.lua │ │ ├── python │ │ │ └── huffman.py │ │ ├── rust │ │ │ ├── Cargo.toml │ │ │ └── huffman.rs │ │ ├── scala │ │ │ └── huffman_encoding.scala │ │ └── scratch │ │ │ ├── huffman.svg │ │ │ └── huffman.txt │ ├── huffman_encoding.md │ └── res │ │ └── huffman_tree.png ├── introduction │ └── introduction.md ├── jarvis_march │ ├── code │ │ ├── c │ │ │ └── jarvis_march.c │ │ ├── clisp │ │ │ └── jarvis-march.lisp │ │ ├── coconut │ │ │ └── jarvis_march.coco │ │ ├── cpp │ │ │ └── jarvis_march.cpp │ │ ├── csharp │ │ │ ├── JarvisMarch.cs │ │ │ └── Program.cs │ │ ├── go │ │ │ └── jarvis.go │ │ ├── haskell │ │ │ └── jarvisMarch.hs │ │ ├── java │ │ │ └── JarvisMarch.java │ │ ├── javascript │ │ │ └── jarvis-march.js │ │ ├── julia │ │ │ └── jarvis.jl │ │ ├── python │ │ │ └── jarvis_march.py │ │ ├── rust │ │ │ └── jarvis_march.rs │ │ └── v │ │ │ └── jarvis.v │ └── jarvis_march.md ├── makefiles │ └── makefiles.md ├── mathematical_background │ └── mathematical_background.md ├── matrix_methods │ └── matrix_methods.md ├── monte_carlo_integration │ ├── code │ │ ├── asm-x64 │ │ │ └── monte_carlo.s │ │ ├── bash │ │ │ └── monte_carlo.bash │ │ ├── c │ │ │ └── monte_carlo.c │ │ ├── clisp │ │ │ └── monte-carlo.lisp │ │ ├── clojure │ │ │ └── monte_carlo.clj │ │ ├── coconut │ │ │ └── monte_carlo.coco │ │ ├── cpp │ │ │ └── monte_carlo.cpp │ │ ├── csharp │ │ │ ├── Circle.cs │ │ │ ├── MonteCarlo.cs │ │ │ └── Program.cs │ │ ├── d │ │ │ └── monte_carlo.d │ │ ├── emojicode │ │ │ └── monte_carlo.emojic │ │ ├── factor │ │ │ └── monte_carlo.factor │ │ ├── fortran │ │ │ └── monte_carlo.f90 │ │ ├── go │ │ │ └── monteCarlo.go │ │ ├── haskell │ │ │ └── monteCarlo.hs │ │ ├── java │ │ │ └── MonteCarlo.java │ │ ├── javascript │ │ │ └── monte_carlo.js │ │ ├── julia │ │ │ └── monte_carlo.jl │ │ ├── kotlin │ │ │ └── MonteCarlo.kt │ │ ├── lua │ │ │ └── monte_carlo.lua │ │ ├── matlab │ │ │ └── monte.m │ │ ├── nim │ │ │ └── monte_carlo.nim │ │ ├── php │ │ │ └── monte_carlo.php │ │ ├── powershell │ │ │ └── MonteCarlo.ps1 │ │ ├── python │ │ │ └── monte_carlo.py │ │ ├── r │ │ │ └── monte_carlo.R │ │ ├── racket │ │ │ └── monte_carlo.rkt │ │ ├── ruby │ │ │ └── monte_carlo.rb │ │ ├── rust │ │ │ ├── Cargo.toml │ │ │ └── monte_carlo.rs │ │ ├── scala │ │ │ └── monte_carlo.scala │ │ ├── scratch │ │ │ ├── Algorithm.svg │ │ │ ├── InCircle.svg │ │ │ └── monte_carlo.txt │ │ └── swift │ │ │ └── monte_carlo.swift │ ├── monte_carlo_integration.md │ └── res │ │ ├── 13311.png │ │ ├── 195583.png │ │ ├── 31.png │ │ ├── monte_carlo.gif │ │ └── square_circle.png ├── multiplication │ └── multiplication.md ├── my_introduction_to_hobby_programming │ └── my_introduction_to_hobby_programming.md ├── notation │ ├── notation.md │ ├── out.dat │ └── res │ │ └── cplot.png ├── physics_solvers │ └── physics_solvers.md ├── plotting │ ├── code │ │ └── gnuplot │ │ │ ├── example_tex.gp │ │ │ ├── histogram.gp │ │ │ ├── latex_import.tex │ │ │ ├── sine.gp │ │ │ └── sine_to_file.gp │ ├── data │ │ ├── 1d_sample_data.dat │ │ ├── 1d_sample_low_res.dat │ │ ├── 2d_sample_data.dat │ │ ├── 2d_sample_low_res.dat │ │ ├── rand.dat │ │ └── scatterplot_data.dat │ ├── plotting.md │ └── res │ │ ├── gnuplot │ │ ├── 1d_sample.png │ │ ├── 2d_sample.png │ │ ├── 2d_sample_cb.png │ │ ├── exp.png │ │ ├── explog.png │ │ ├── exponential_tex.png │ │ ├── histogram.png │ │ ├── scatterplot.png │ │ ├── sincos.png │ │ ├── sincos_customtics.png │ │ ├── sincos_label.png │ │ ├── sincos_log.png │ │ ├── sincos_lt.png │ │ ├── sincos_movekey.png │ │ ├── sincos_movekey2.png │ │ ├── sincos_nokey.png │ │ ├── sincos_notics.png │ │ ├── sincos_range.png │ │ ├── sincos_square.png │ │ ├── sincos_title.png │ │ ├── sine.png │ │ └── test.png │ │ └── sincos_lt.png ├── quantum_information │ └── quantum_information.md ├── quantum_systems │ ├── quantum_systems.md │ └── res │ │ └── gaussian.gif ├── split-operator_method │ ├── code │ │ ├── c │ │ │ ├── SConscript │ │ │ └── split_op.c │ │ ├── cpp │ │ │ ├── SConscript │ │ │ └── split_op.cpp │ │ ├── gnuplot │ │ │ └── plot_output.plt │ │ ├── haskell │ │ │ └── splitOp.hs │ │ ├── julia │ │ │ └── split_op.jl │ │ ├── python │ │ │ └── split_op.py │ │ └── rust │ │ │ ├── Cargo.toml │ │ │ └── split_op.rs │ ├── res │ │ ├── Psi_t.png │ │ ├── Psi_tdt.png │ │ ├── imaginary_time.gif │ │ ├── imaginary_time.png │ │ ├── imaginary_time_0.png │ │ ├── imaginary_time_75.png │ │ ├── real_time.gif │ │ ├── real_time.png │ │ ├── real_time_0.png │ │ ├── real_time_75.png │ │ ├── split_op_method.svg │ │ ├── times_Uk.png │ │ └── times_Ur.png │ └── split-operator_method.md ├── stable_marriage_problem │ ├── code │ │ ├── c │ │ │ └── stable_marriage.c │ │ ├── cpp │ │ │ └── stable_marriage.cpp │ │ ├── csharp │ │ │ ├── GaleShapleyAlgorithm.cs │ │ │ ├── ListExtensions.cs │ │ │ ├── Person.cs │ │ │ └── Program.cs │ │ ├── haskell │ │ │ └── stableMarriage.hs │ │ ├── java │ │ │ └── stable-marriage.java │ │ ├── javascript │ │ │ └── stable-marriage.js │ │ ├── julia │ │ │ └── stable_marriage.jl │ │ ├── php │ │ │ └── stable_marriage.php │ │ ├── python │ │ │ └── stable_marriage.py │ │ ├── ruby │ │ │ └── stable_marriage.rb │ │ └── scala │ │ │ └── stable_marriage.scala │ └── stable_marriage_problem.md ├── stacks_and_queues │ ├── code │ │ ├── java │ │ │ ├── Queue.java │ │ │ └── Stack.java │ │ └── typescript │ │ │ ├── queue.ts │ │ │ └── stack.ts │ └── stacks_and_queues.md ├── taylor_series_expansion │ ├── res │ │ └── function_sum.png │ └── taylor_series_expansion.md ├── thomas_algorithm │ ├── code │ │ ├── c │ │ │ └── thomas.c │ │ ├── clisp │ │ │ └── thomas.lisp │ │ ├── cpp │ │ │ └── thomas.cpp │ │ ├── crystal │ │ │ └── thomas.cr │ │ ├── go │ │ │ └── thomas.go │ │ ├── haskell │ │ │ └── thomas.hs │ │ ├── java │ │ │ └── Thomas.java │ │ ├── javascript │ │ │ └── thomas.js │ │ ├── julia │ │ │ └── thomas.jl │ │ ├── kotlin │ │ │ └── thomas.kt │ │ ├── lua │ │ │ └── thomas.lua │ │ ├── nim │ │ │ └── thomas_algorithm.nim │ │ ├── php │ │ │ └── thomas.php │ │ ├── python │ │ │ └── thomas.py │ │ ├── ruby │ │ │ └── thomas.rb │ │ ├── rust │ │ │ └── thomas.rs │ │ ├── scratch │ │ │ ├── thomas.svg │ │ │ └── thomas.txt │ │ ├── swift │ │ │ └── thomas.swift │ │ └── v │ │ │ └── thomas.v │ └── thomas_algorithm.md ├── tree_traversal │ ├── code │ │ ├── asm-x64 │ │ │ └── tree_traversal.s │ │ ├── c │ │ │ ├── tree_traversal.c │ │ │ └── utility.h │ │ ├── clisp │ │ │ └── tree-traversal.lisp │ │ ├── coconut │ │ │ └── tree_traversal.coco │ │ ├── cpp │ │ │ └── tree_example.cpp │ │ ├── crystal │ │ │ └── tree-traversal.cr │ │ ├── csharp │ │ │ ├── Program.cs │ │ │ ├── Tree.cs │ │ │ └── code.csproj │ │ ├── emojicode │ │ │ └── tree_traversal.emojic │ │ ├── go │ │ │ └── treetraversal.go │ │ ├── haskell │ │ │ └── TreeTraversal.hs │ │ ├── java │ │ │ ├── MainClass.java │ │ │ └── Tree.java │ │ ├── javascript │ │ │ └── tree.js │ │ ├── julia │ │ │ └── Tree.jl │ │ ├── matlab │ │ │ └── tree.m │ │ ├── ocaml │ │ │ └── tree.ml │ │ ├── php │ │ │ └── tree_traversal.php │ │ ├── python │ │ │ └── tree_traversal.py │ │ ├── rust │ │ │ └── tree.rs │ │ ├── scratch │ │ │ ├── all.svg │ │ │ ├── bfs.svg │ │ │ ├── dfs-in.svg │ │ │ ├── dfs-post.svg │ │ │ ├── dfs-pre.svg │ │ │ ├── dfs-stack.svg │ │ │ ├── struct.svg │ │ │ └── tree_traversal.txt │ │ ├── smalltalk │ │ │ └── tree_traversal.st │ │ └── swift │ │ │ └── tree.swift │ ├── res │ │ ├── 3-tree.png │ │ ├── BFS_simple.png │ │ ├── DFS_in.png │ │ ├── DFS_post.png │ │ ├── DFS_pre.png │ │ └── binary_tree.png │ └── tree_traversal.md └── verlet_integration │ ├── code │ ├── asm-x64 │ │ └── verlet.s │ ├── c │ │ └── verlet.c │ ├── clisp │ │ └── verlet.lisp │ ├── cpp │ │ └── verlet.cpp │ ├── fortran │ │ └── verlet.f90 │ ├── go │ │ └── verlet.go │ ├── haskell │ │ └── verlet.hs │ ├── java │ │ └── Verlet.java │ ├── javascript │ │ └── verlet.js │ ├── julia │ │ └── verlet.jl │ ├── kotlin │ │ └── verlet.kt │ ├── labview │ │ └── verlet_labview.png │ ├── matlab │ │ └── verlet.m │ ├── nim │ │ └── verlet.nim │ ├── python │ │ └── verlet.py │ ├── ruby │ │ └── verlet.rb │ ├── rust │ │ └── verlet.rs │ ├── scratch │ │ └── verlet_scratch.png │ └── swift │ │ └── verlet.swift │ └── verlet_integration.md ├── literature.bib ├── math.md ├── package.json ├── redirects.json ├── res └── languages.gif ├── sconscripts ├── asm-x64_SConscript ├── c_SConscript ├── cpp_SConscript ├── fortran_SConscript ├── go_SConscript └── rust_SConscript ├── styles └── website.css └── tools ├── cleanup ├── clean_book_json.py └── clean_editorconfig.py ├── deploy └── update_site_travis.bash └── hooks ├── README.md ├── install_hooks.bash └── pre-commit.hook /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: LLVM 2 | 3 | AlignAfterOpenBracket: AlwaysBreak 4 | AlwaysBreakTemplateDeclarations: true 5 | BinPackArguments: false 6 | BinPackParameters: false 7 | PointerAlignment: Left 8 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. 2 | { 3 | "name": "Arcane Algorithm Archive All Languages", 4 | 5 | // Comment out 'image' and uncomment 'build' to test changes to the dockerfile locally 6 | "image": "ghcr.io/algorithm-archivists/aaa-langs:latest", 7 | // "build": {\ 8 | // // For config options, see the README at:https://github.com/microsoft/vscode-dev-containers/tree/v0.187.0/containers/ubuntu 9 | // "dockerfile": "../Dockerfile", 10 | // // Update 'VARIANT' to pick an Ubuntu version: focal, bionic 11 | // "args": { "VARIANT": "focal" } 12 | // }, 13 | 14 | // Set *default* container specific settings.json values on container create. 15 | "settings": {}, 16 | 17 | // Add the IDs of extensions you want installed when the container is created. 18 | "extensions": [], 19 | 20 | // Use 'forwardPorts' to make a list of ports inside the container available locally (outside the container). 21 | // Port : Usage 22 | // 4000 : Honkit serves by default on this port 23 | "forwardPorts": [4000] 24 | } 25 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Force all text files to have LF line endings 2 | * text=auto eol=lf 3 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: leios 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2'] 13 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/FEATURE_REQUEST.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature Request 3 | about: Requesting a new feature to be in the Algorithm Archive 4 | --- 5 | 6 | 13 | 14 | # Feature Request 15 | 16 | ## Description 17 | 18 | A clear and concise description of what the desired feature is and how it would help, including any relevant screenshots / schematics. 19 | 20 | ## Additional context 21 | 22 | Add any other reasons why this feature will help with the goals of the Algorithm Archive. 23 | 24 | 25 | 26 | 27 | ## For Algorithm Archive Developers 28 | 29 | - [ ] This feature can be added to the [Master Overview](https://github.com/algorithm-archivists/algorithm-archive/projects/11) (if it cannot be, explain why in a comment below -- lack of technical expertise, not relevant to the scope of this project, too ambitious) 30 | - [ ] There is a timeline for when this feature can be implemented 31 | - [ ] The feature has been added to the [Master Overview](https://github.com/algorithm-archivists/algorithm-archive/projects/11) 32 | - [ ] The feature has been implemented (Please link the PR) 33 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | on: pull_request 3 | 4 | jobs: 5 | build: 6 | runs-on: ubuntu-latest 7 | steps: 8 | - name: Checkout 9 | uses: actions/checkout@v2 10 | with: 11 | persist-credentials: false 12 | 13 | - name: Install and build 14 | run: | 15 | npm install 16 | npx honkit build 17 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: Build and Deploy 2 | on: 3 | push: 4 | branches: 5 | - main 6 | 7 | jobs: 8 | build-and-deploy: 9 | runs-on: ubuntu-latest 10 | if: github.repository == 'algorithm-archivists/algorithm-archive' 11 | steps: 12 | - name: Checkout 13 | uses: actions/checkout@v2 14 | with: 15 | persist-credentials: false 16 | 17 | - name: Install and build 18 | run: | 19 | npm install 20 | npx honkit build 21 | 22 | - name: Deploy 23 | uses: JamesIves/github-pages-deploy-action@4.1.4 24 | with: 25 | branch: gh-pages 26 | folder: _book 27 | -------------------------------------------------------------------------------- /.github/workflows/issue_comment.yml: -------------------------------------------------------------------------------- 1 | name: Add Label with Comment 2 | 3 | on: [issue_comment] 4 | 5 | jobs: 6 | create_comment: 7 | runs-on: ubuntu-latest 8 | steps: 9 | - uses: actions-ecosystem/action-regex-match@v2 10 | id: regex-match 11 | with: 12 | text: ${{ github.event.comment.body }} 13 | regex: '\[lang:\s*(.*?)\s*\]' 14 | 15 | - uses: actions-ecosystem/action-add-labels@v1 16 | if: ${{ steps.regex-match.outputs.match != '' }} 17 | with: 18 | github_token: ${{ secrets.GITHUB_TOKEN }} 19 | labels: "lang: ${{ steps.regex-match.outputs.group1 }}" 20 | -------------------------------------------------------------------------------- /.github/workflows/publish_container.yml: -------------------------------------------------------------------------------- 1 | name: Publish Docker 2 | on: 3 | push: 4 | branches: 5 | - main 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | if: github.repository == 'algorithm-archivists/algorithm-archive' 10 | steps: 11 | - uses: actions/checkout@master 12 | - name: Publish to Registry 13 | uses: elgohr/Publish-Docker-Github-Action@master 14 | with: 15 | name: algorithm-archivists/aaa-langs 16 | username: ${{ github.actor }} 17 | password: ${{ secrets.GITHUB_TOKEN }} 18 | registry: ghcr.io 19 | -------------------------------------------------------------------------------- /.nojekyll: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/.nojekyll -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Code of Conduct 4 | 5 | Please note that this project is released with a [Contributor Code of Conduct](./CODE_OF_CONDUCT.md). 6 | By participating in this project you agree to abide by its terms. 7 | 8 | More information regarding the Code of Conduct can be found in the 9 | [Code of Conduct wiki entry](https://github.com/algorithm-archivists/algorithm-archive/wiki/Code-of-Conduct). 10 | 11 | ## How to Contribute 12 | 13 | A contribution guide on how to contribute to the Arcane Algorithm Archive (AAA) can be found on this Wiki page: https://github.com/algorithm-archivists/algorithm-archive/wiki/How-to-Contribute 14 | 15 | The community member Buttercak3 also created a video series, explaining the contribution process of the AAA. You can find a playlist with all videos here: https://www.youtube.com/playlist?list=PL5NSPcN6fRq2vwgdb9noJacF945CeBk8x 16 | -------------------------------------------------------------------------------- /CONTRIBUTORS.md: -------------------------------------------------------------------------------- 1 | This file lists everyone, who contributed to this repo and wanted to show up here. If you're looking for information on contribution, please check the `CONTRIBUTING.md` out. 2 | 3 | # Contributors 4 | 5 | - James Schloss 6 | - Nicole Mazzuca 7 | - Marius Becker 8 | - Gathros 9 | - Jeremie Gillet (- Jie -) 10 | - Salim Khatib 11 | - Hitesh C 12 | - Shaurya 13 | - Maxime Dherbécourt 14 | - Jess 3Jane 15 | - Pen Pal 16 | - Chinmaya Mahesh 17 | - Unlambder 18 | - Kjetil Johannessen 19 | - CDsigma 20 | - Gammison 21 | - hsjoihs 22 | - DominikRafacz 23 | - lulucca12 24 | - GuyPozner 25 | - William Boyles 26 | - Max Weinstein 27 | - Gibus Wearing Brony 28 | - Gorzoid 29 | - Arun Sahadeo 30 | - NIFR91 31 | - Michal Hanajik 32 | - Bendik Samseth 33 | - mukundan314 34 | - Trashtalk 35 | - Cyrus Burt 36 | - Patrik Tesarik 37 | - Ken Power 38 | - PaddyKe 39 | - nic-hartley 40 | - Thijs Raymakers 41 | - crafter312 42 | - Christopher Milan 43 | - Vexatos 44 | - Raven-Blue Dragon 45 | - Björn Heinrichs 46 | - Olav Sundfør 47 | - Ben Chislett 48 | - dovisutu 49 | - Antetokounpo 50 | - Akash Dhiman 51 | - Vincent Zalzal 52 | - Jonathan D B Van Schenck 53 | - James Goytia 54 | - Sammy Plat 55 | - Jonathan Dönszelmann 56 | - Ishaan Verma 57 | - Delphi1024 58 | - ntindle 59 | - Mahdi Sarikhani 60 | - Ridham177 61 | - Hugo Salou 62 | - Dimitri Belopopsky 63 | + Henrik Abel Christensen 64 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2018 James Schloss et. al 2 | 3 | Permission is hereby granted, free of charge, to any person 4 | obtaining a copy of this software and associated documentation 5 | files (the "Software"), to deal in the Software without 6 | restriction, including without limitation the rights to use, 7 | copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | copies of the Software, and to permit persons to whom the 9 | Software is furnished to do so, subject to the following 10 | conditions: 11 | 12 | The above copyright notice and this permission notice shall be 13 | included in all copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 16 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 17 | OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 18 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT 19 | HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, 20 | WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 21 | FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 22 | OTHER DEALINGS IN THE SOFTWARE. 23 | -------------------------------------------------------------------------------- /contents/IFS/code/c/IFS.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | 6 | struct point { 7 | double x, y; 8 | }; 9 | 10 | double drand() { 11 | return ((double) rand() / (RAND_MAX)); 12 | } 13 | 14 | struct point random_element(struct point *array, size_t n) { 15 | return array[rand() % (int)n]; 16 | } 17 | 18 | void chaos_game(struct point *in, size_t in_n, struct point *out, 19 | size_t out_n) { 20 | 21 | struct point cur_point = {drand(), drand()}; 22 | 23 | for (size_t i = 0; i < out_n; ++i) { 24 | out[i] = cur_point; 25 | struct point tmp = random_element(in, in_n); 26 | cur_point.x = 0.5 * (cur_point.x + tmp.x); 27 | cur_point.y = 0.5 * (cur_point.y + tmp.y); 28 | } 29 | } 30 | 31 | int main() { 32 | const int point_count = 10000; 33 | 34 | struct point shape_points [3] = {{0.0,0.0}, {0.5,sqrt(0.75)}, {1.0,0.0}}; 35 | struct point out_points[point_count]; 36 | 37 | srand(time(NULL)); 38 | 39 | chaos_game(shape_points, 3, out_points, point_count); 40 | 41 | FILE *fp = fopen("sierpinksi.dat", "w+"); 42 | 43 | for (int i = 0; i < point_count; ++i) { 44 | fprintf(fp, "%f\t%f\n", out_points[i].x, out_points[i].y); 45 | } 46 | 47 | fclose(fp); 48 | 49 | return 0; 50 | } 51 | -------------------------------------------------------------------------------- /contents/IFS/code/clisp/ifs.lisp: -------------------------------------------------------------------------------- 1 | ;;;; Iterated Function System implementation 2 | 3 | (defstruct (point (:constructor make-point (x y))) x y) 4 | 5 | (defun chaos-game (iterations shape-points) 6 | "Plays a chaos game with a certain shape for a determined amount of iterations" 7 | (loop 8 | repeat iterations 9 | for rand-point = (svref shape-points (random (length shape-points))) 10 | for point = (make-point (random 1.0) (random 1.0)) ; starting point 11 | then (make-point 12 | (* 0.5 (+ (point-x rand-point) (point-x point))) 13 | (* 0.5 (+ (point-y rand-point) (point-y point)))) ; every subsequent point 14 | collect point)) 15 | 16 | (defparameter *shape-points* 17 | (map 18 | 'vector 19 | (lambda (e) (apply #'make-point e)) 20 | ;; the backquote allows us to selectively evaluate (sqrt 0.75) with the comma 21 | `((0 0) (0.5 ,(sqrt 0.75)) (1 0)))) 22 | 23 | ;; output the data to the "out.dat" file 24 | (with-open-file (out "sierpinski.dat" :direction :output :if-exists :supersede) 25 | (flet ((format-point (p) 26 | ;; this is not very clean, but it's the simplest way to insert a tab into a string. 27 | (format nil "~f~c~f" (point-x p) #\tab (point-y p)))) 28 | (format out "~{~a~%~}" (map 'list #'format-point (chaos-game 10000 *shape-points*))))) 29 | -------------------------------------------------------------------------------- /contents/IFS/code/coconut/IFS.coco: -------------------------------------------------------------------------------- 1 | from math import sqrt 2 | from random import random, choice 3 | 4 | data point(x=0, y=0): 5 | def __add__(self, other): 6 | return point(self.x + other.x, self.y + other.y) 7 | 8 | def __rmul__(self, other): 9 | return point(self.x * other, self.y * other) 10 | 11 | def chaos_game(n, shape_points): 12 | p = point(random(), random()) 13 | 14 | for _ in range(n): 15 | p = (1/2) * (p + choice(shape_points)) 16 | yield p 17 | 18 | 19 | # This will generate a Sierpinski triangle with a chaos game of n points for an 20 | # initial triangle with three points on the vertices of an equilateral triangle: 21 | # A = (0.0, 0.0) 22 | # B = (0.5, sqrt(0.75)) 23 | # C = (1.0, 0.0) 24 | # It will output the file sierpinski.dat, which can be plotted after 25 | shape_points = [point(0.0, 0.0), 26 | point(0.5, sqrt(0.75)), 27 | point(1.0, 0.0)] 28 | with open("sierpinski.dat", "w") as f: 29 | for p in chaos_game(10000, shape_points): 30 | f.write("{0}\t{1}\n".format(p.x, p.y)) 31 | -------------------------------------------------------------------------------- /contents/IFS/code/haskell/IFS.hs: -------------------------------------------------------------------------------- 1 | import Data.Array ((!), Array, bounds, listArray) 2 | import Data.List (intercalate) 3 | import System.Random 4 | 5 | data Point = Point Double Double 6 | 7 | chaosGame :: RandomGen g => g -> Int -> Array Int (Point -> Point) -> [Point] 8 | chaosGame g n hutchinson = take n points 9 | where 10 | (x, g') = random g 11 | (y, g'') = random g' 12 | choices = randomRs (bounds hutchinson) g'' 13 | points = Point x y : zipWith (hutchinson !) choices points 14 | 15 | main :: IO () 16 | main = do 17 | g <- newStdGen 18 | 19 | let midPoint (Point a b) (Point x y) = Point ((a + x) / 2) ((b + y) / 2) 20 | sierpinski = 21 | listArray 22 | (1, 3) 23 | [ midPoint (Point 0 0), 24 | midPoint (Point 0.5 (sqrt 0.75)), 25 | midPoint (Point 1 0) 26 | ] 27 | points = chaosGame g 10000 sierpinski 28 | showPoint (Point x y) = show x ++ "\t" ++ show y 29 | 30 | writeFile "sierpinski.dat" $ intercalate "\n" $ map showPoint points 31 | -------------------------------------------------------------------------------- /contents/IFS/code/julia/IFS.jl: -------------------------------------------------------------------------------- 1 | using DelimitedFiles 2 | 3 | # This is a function to simulate a "chaos game" 4 | function chaos_game(n::Int, shape_points) 5 | 6 | # Initializing the output array and the initial point 7 | output_points = zeros(n,2) 8 | point = [rand(), rand()] 9 | 10 | for i = 1:n 11 | output_points[i,:] .= point 12 | point = 0.5*(rand(shape_points) .+ point) 13 | end 14 | 15 | return output_points 16 | 17 | end 18 | 19 | # This will generate a Sierpinski triangle with a chaos game of n points for an 20 | # initial triangle with three points on the vertices of an equilateral triangle: 21 | # A = (0.0, 0.0) 22 | # B = (0.5, sqrt(0.75)) 23 | # C = (1.0, 0.0) 24 | # It will output the file sierpinski.dat, which can be plotted after 25 | shape_points = [[0.0, 0.0], 26 | [0.5, sqrt(0.75)], 27 | [1.0, 0.0]] 28 | output_points = chaos_game(10000, shape_points) 29 | writedlm("sierpinski.dat", output_points) 30 | -------------------------------------------------------------------------------- /contents/IFS/code/powershell/IFS.ps1: -------------------------------------------------------------------------------- 1 | # This function simulates a "chaos game" 2 | function Simulate-ChaosGame($n, $shapePoints) { 3 | $outputPoints = New-Object System.Collections.ArrayList 4 | 5 | # Initialize the starting point 6 | $point = @($(Get-Random -Minimum 0.0 -Maximum 1.0), $(Get-Random -Minimum 0.0 -Maximum 1.0)) 7 | 8 | for ($i = 0; $i -lt $n; $i++) { 9 | $outputPoints.add($point) | Out-Null 10 | $temp = $shapePoints[$(Get-Random -Maximum $shapePoints.Count)] 11 | 12 | $point = @( 13 | 0.5 * ($point[0] + $temp[0]) 14 | 0.5 * ($point[1] + $temp[1]) 15 | ) 16 | } 17 | 18 | return $outputPoints 19 | } 20 | 21 | 22 | # This will generate a Sierpinski triangle with a chaos game of n points for an 23 | # initial triangle with three points on the vertices of an equilateral triangle: 24 | # A = (0.0, 0.0) 25 | # B = (0.5, sqrt(0.75)) 26 | # C = (1.0, 0.0) 27 | # It will output the file sierpinski.dat, which can be plotted after 28 | $shapePoints = @( 29 | @(0.0, 0.0), 30 | @(0.5, [math]::sqrt(0.75)), 31 | @(1.0, 0.0) 32 | ) 33 | 34 | Simulate-ChaosGame -n 10000 -shapePoints $shapePoints | % { "$($_[0])`t$($_[1])" } | Out-File -Path "sierpinski.dat" 35 | -------------------------------------------------------------------------------- /contents/IFS/code/python/IFS.py: -------------------------------------------------------------------------------- 1 | from random import random, choice 2 | from math import sqrt 3 | 4 | # This generator simulates a "chaos game" 5 | def chaos_game(n, shape_points): 6 | # Initialize the starting point 7 | point = [random(), random()] 8 | 9 | for _ in range(n): 10 | # Update the point position and yield the result 11 | point = [(p + s) / 2 for p, s in zip(point, choice(shape_points))] 12 | yield point 13 | 14 | # This will generate a Sierpinski triangle with a chaos game of n points for an 15 | # initial triangle with three points on the vertices of an equilateral triangle: 16 | # A = (0.0, 0.0) 17 | # B = (0.5, sqrt(0.75)) 18 | # C = (1.0, 0.0) 19 | # It will output the file sierpinski.dat, which can be plotted after 20 | shape_points = [[0.0, 0.0], 21 | [0.5, sqrt(0.75)], 22 | [1.0, 0.0]] 23 | with open("sierpinski.dat", "w") as f: 24 | for point in chaos_game(10000, shape_points): 25 | f.write("{0}\t{1}\n".format(*point)) 26 | -------------------------------------------------------------------------------- /contents/IFS/res/IFS_square_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_square_1.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_square_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_square_2.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_square_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_square_3.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_square_vid_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_square_vid_1.mp4 -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_1.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_2.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_3.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_4.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_5.png -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_vid_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_vid_1.mp4 -------------------------------------------------------------------------------- /contents/IFS/res/IFS_triangle_vid_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/IFS_triangle_vid_2.mp4 -------------------------------------------------------------------------------- /contents/IFS/res/chaos_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/chaos_1.png -------------------------------------------------------------------------------- /contents/IFS/res/chaos_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/chaos_2.png -------------------------------------------------------------------------------- /contents/IFS/res/chaos_vid_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/chaos_vid_1.mp4 -------------------------------------------------------------------------------- /contents/IFS/res/chaos_vid_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/IFS/res/chaos_vid_2.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a11_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a11_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a11_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a11_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a12_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a12_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a12_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a12_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a13_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a13_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a13_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a13_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a21_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a21_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a21_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a21_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a22_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a22_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a22_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a22_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a23_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a23_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a23_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a23_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a31_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a31_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a32_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a32_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/a33_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/a33_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/cosines_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/cosines_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/rotation_cube_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/rotation_cube_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/rotation_square_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/rotation_square_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/semi_rotate_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/semi_rotate_white.mp4 -------------------------------------------------------------------------------- /contents/affine_transformations/res/sines_white.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/affine_transformations/res/sines_white.mp4 -------------------------------------------------------------------------------- /contents/approximate_counting/code/c/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') 7 | -------------------------------------------------------------------------------- /contents/approximate_counting/res/a_change.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/a_change.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/approximations.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/approximations.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/approximationsexp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/approximationsexp.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/deltas.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/deltas.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/hands.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/hands.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/hist_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/hist_1.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/hist_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/hist_2.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/hist_2_plot.gp: -------------------------------------------------------------------------------- 1 | set terminal epslatex standalone color 2 | 3 | #set output "histexp_1.tex" 4 | #set output "histexp_2.tex" 5 | set output "histexp_3.tex" 6 | 7 | set size square 8 | 9 | #set title "True count of 10,000" 10 | #set title "True count of 500,000" 11 | set title "True count of 1,000,000" 12 | 13 | set xlabel '' 14 | #set xrange [-255:9745] 15 | #set xtics ("6000" -255, "10,000" 3745, "16,000" 9745) 16 | 17 | #set xrange [352000:644000] 18 | #set xrange[-1458:538542] 19 | #set xtics ("320,000" -1458, "500,000" 178542, "860,000" 538542) 20 | 21 | #set xrange [808000:1240000] 22 | set xrange[-19374:1100626] 23 | set xtics ("600,0000" -19374, "1,000,000" 380626, "1,720,000" 1100626) 24 | 25 | #set ylabel 'Approximate count $\left( \times 10^{5} \right)$' 26 | #set ytics ("0" 0, "2" 200000, "4" 400000, "6" 600000, "8" 800000, "10" 1000000) 27 | 28 | #plot "histogram_1exp.dat" w l lw 10 title "" 29 | #plot "histogram_2exp.dat" w l lw 10 title "" 30 | plot "histogram_3exp.dat" w l lw 10 title "" 31 | 32 | -------------------------------------------------------------------------------- /contents/approximate_counting/res/hist_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/hist_3.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/hist_plot.gp: -------------------------------------------------------------------------------- 1 | set terminal epslatex standalone color 2 | 3 | #set output "hist_1.tex" 4 | #set output "hist_2.tex" 5 | set output "hist_3.tex" 6 | 7 | set size square 8 | 9 | #set title "True count of 10,000" 10 | #set title "True count of 500,000" 11 | set title "True count of 1,000,000" 12 | 13 | #set xlabel '' 14 | #set xrange [0:40000] 15 | #set xtics ("0" 0, "20,000" 20000, "40,000" 40000) 16 | 17 | #set xrange [352000:644000] 18 | #set xrange[10000:310000] 19 | #set xtics ("350,000" 10000, "500,000" 160000, "650,000" 310000) 20 | 21 | #set xrange [808000:1240000] 22 | set xrange[-10000:490000] 23 | set xtics ("750,0000" -10000, "1,000,000" 240000, "1,250,000" 490000) 24 | 25 | #set ylabel 'Approximate count $\left( \times 10^{5} \right)$' 26 | #set ytics ("0" 0, "2" 200000, "4" 400000, "6" 600000, "8" 800000, "10" 1000000) 27 | 28 | #plot "histogram_1.dat" w l lw 10 title "" 29 | #plot "histogram_2.dat" w l lw 10 title "" 30 | plot "histogram_3.dat" w l lw 10 title "" 31 | 32 | -------------------------------------------------------------------------------- /contents/approximate_counting/res/histexp_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/histexp_1.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/histexp_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/histexp_2.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/histexp_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/histexp_3.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/histograms.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/approximate_counting/res/histograms.png -------------------------------------------------------------------------------- /contents/approximate_counting/res/plot.gp: -------------------------------------------------------------------------------- 1 | set terminal epslatex standalone color 2 | #set terminal pdf enhanced 3 | #set style fill transparent solid 0.3 4 | 5 | #set output "check.tex" 6 | set output "checkexp.tex" 7 | #set size square 8 | 9 | set title "Approximate counting of 1,000,000 items" 10 | 11 | set xlabel 'True number of items $\left( \times 10^{5} \right)$' 12 | set xtics ("0" 0, "2" 200000, "4" 400000, "6" 600000, "8" 800000, "10" 1000000) 13 | 14 | set ylabel 'Approximate count $\left( \times 10^{5} \right)$' 15 | set ytics ("0" 0, "2" 200000, "4" 400000, "6" 600000, "8" 800000, "10" 1000000, "12" 1200000, "14" 1400000) 16 | 17 | #plot "extremes.dat" u 0:1:2 w filledcu lc "gray" title "", for [i=1:10] "out.dat" u 0:i w l lw 3 title "", x w l lw 3 dt 3 lc "black" title "" 18 | plot "extremesexp.dat" u 0:1:2 w filledcu lc "gray" title "", for [i=1:10] "outexp.dat" u 0:i w l lw 3 title "", x w l lw 3 dt 3 lc "black" title "" 19 | 20 | -------------------------------------------------------------------------------- /contents/approximate_counting/res/plot_a.gp: -------------------------------------------------------------------------------- 1 | set terminal epslatex standalone color 2 | 3 | set output "a_change.tex" 4 | #set size square 5 | 6 | set title '$n_v$ vs $a$ for $v=255$' 7 | 8 | set xlabel '$a$' 9 | set xtics ("25" 0, "27.5" 5, "30" 10, "32.5" 15, "35" 20) 10 | 11 | set ylabel '$n_v (\times 10^5)$' 12 | set ytics ("0" 0, "1" 100000, "2" 200000, "3" 300000, "4" 400000, "5" 500000) 13 | 14 | plot for [i=1:10] "a_change.dat" w l lw 3 title "" 15 | 16 | -------------------------------------------------------------------------------- /contents/approximate_counting/res/plot_deltas.gp: -------------------------------------------------------------------------------- 1 | set terminal epslatex standalone color 2 | 3 | set output "deltas.tex" 4 | #set size square 5 | 6 | set title '$\Delta$ vs $v$' 7 | 8 | set xlabel '$v$' 9 | 10 | set ylabel '$\Delta$ (logscale)' 11 | set logscale y 12 | 13 | plot for [i=1:10] "deltas.dat" w l lw 3 title "" 14 | 15 | -------------------------------------------------------------------------------- /contents/backward_euler_method/backward_euler_method.md: -------------------------------------------------------------------------------- 1 | # Backward Euler Method 2 | 3 | Unlike the forward Euler Method above, the backward Euler Method is an *implicit method*, which means that it results in a system of equations to solve. Luckily, we know how to solve systems of equations (*hint*: [Thomas Algorithm](../thomas_algorithm/thomas_algorithm.md), [Gaussian Elimination](../gaussian_elimination/gaussian_elimination.md)) 4 | 5 | MORE TO COME!!! 6 | 7 | 8 | 11 | 12 | ## License 13 | 14 | ##### Code Examples 15 | 16 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 17 | 18 | ##### Text 19 | 20 | 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). 21 | 22 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 23 | 24 | ##### Pull Requests 25 | 26 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 27 | - none 28 | -------------------------------------------------------------------------------- /contents/barnes_hut_algorithm/barnes_hut_algorithm.md: -------------------------------------------------------------------------------- 1 | ##### Dependencies 2 | * [Verlet Integration](../verlet_integration/verlet_integration.md) 3 | 4 | # Barnes Hut Algorithm 5 | 6 | The Barnes-Hut algorithm divides space into an octree in order to cut computational time without losing much precision in n-body simulations. If you want to learn more soon, bug me about it! 7 | 8 | TODO 9 | 10 | 11 | 14 | 15 | ## License 16 | 17 | ##### Code Examples 18 | 19 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 20 | 21 | ##### Text 22 | 23 | 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). 24 | 25 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 26 | 27 | ##### Pull Requests 28 | 29 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 30 | - none 31 | -------------------------------------------------------------------------------- /contents/barnsley/code/coconut/barnsley.coco: -------------------------------------------------------------------------------- 1 | from random import choices 2 | import numpy as np 3 | 4 | data Point(x=0, y=0): 5 | def __rmatmul__(self, mat: np.array): 6 | point_array = np.array([self.x, self.y, 1]) 7 | x, y, *_ = tuple(*(mat @ point_array)) 8 | return Point(x, y) 9 | 10 | 11 | def chaos_game(initial_location is Point, hutchinson_op, probabilities): 12 | point = initial_location 13 | while True: 14 | yield (point := choices(hutchinson_op, probabilities) @ point) 15 | 16 | barnsley_hutchinson = [ 17 | np.array([ 18 | [0., 0., 0.], 19 | [0., 0.16, 0.], 20 | [0., 0., 1.], 21 | ]), 22 | np.array([ 23 | [0.85, 0.04, 0.], 24 | [-0.04, 0.85, 1.6], 25 | [0., 0., 1.], 26 | ]), 27 | np.array([ 28 | [0.2, -0.26, 0.], 29 | [0.23, 0.22, 1.6], 30 | [0., 0., 1.], 31 | ]), 32 | np.array([ 33 | [-0.15, 0.28, 0.], 34 | [0.26, 0.24, 0.44], 35 | [0., 0., 1.], 36 | ]), 37 | ] 38 | 39 | barnsley_probabilities = [0.01, 0.85, 0.07, 0.07] 40 | 41 | if __name__ == '__main__': 42 | output_gen = chaos_game(Point(0, 0), barnsley_hutchinson, barnsley_probabilities) 43 | output_points = np.array([*output_gen$[:10000]]) 44 | np.savetxt("out.dat", output_points) 45 | -------------------------------------------------------------------------------- /contents/barnsley/code/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "barnsley" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | rand = "0.8.4" 10 | 11 | [[bin]] 12 | path = "./barnsley.rs" 13 | name = "main" -------------------------------------------------------------------------------- /contents/barnsley/res/affine_fern_0.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_fern_0.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_fern_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_fern_1.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_fern_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_fern_2.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_fern_3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_fern_3.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_rnd_0.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_rnd_0.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_rnd_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_rnd_1.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_rnd_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_rnd_2.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/affine_rnd_3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/affine_rnd_3.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/fern_twiddle_0.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/fern_twiddle_0.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/fern_twiddle_1.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/fern_twiddle_1.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/fern_twiddle_2.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/fern_twiddle_2.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/fern_twiddle_3.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/fern_twiddle_3.mp4 -------------------------------------------------------------------------------- /contents/barnsley/res/full_fern.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/barnsley/res/full_fern.png -------------------------------------------------------------------------------- /contents/bitlogic/res/and.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/and.jpg -------------------------------------------------------------------------------- /contents/bitlogic/res/nand.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/nand.jpg -------------------------------------------------------------------------------- /contents/bitlogic/res/nor.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/nor.jpg -------------------------------------------------------------------------------- /contents/bitlogic/res/not.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/not.jpg -------------------------------------------------------------------------------- /contents/bitlogic/res/or.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/or.jpg -------------------------------------------------------------------------------- /contents/bitlogic/res/xor.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/bitlogic/res/xor.jpg -------------------------------------------------------------------------------- /contents/cc/README.txt: -------------------------------------------------------------------------------- 1 | The file `license.txt` is an example license with attribution to James Schloss (Leios). 2 | Please modify it with the appropriate attribution before appending to the end of each chapter. 3 | 4 | To append this license to the end of all files, execute the following command in the `contents/` directory: 5 | find . -name "*.md" -print | xargs sed -i '$r cc/license.txt' 6 | -------------------------------------------------------------------------------- /contents/cc/license.txt: -------------------------------------------------------------------------------- 1 | 2 | ## License 3 | 4 | ##### Code Examples 5 | 6 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 7 | 8 | ##### Text 9 | 10 | 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). 11 | 12 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 13 | 14 | ##### Images/Graphics 15 | - The image "[example Image](res/example.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). 16 | 17 | ##### Pull Requests 18 | 19 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 20 | - none 21 | -------------------------------------------------------------------------------- /contents/chans_algorithm/chans_algorithm.md: -------------------------------------------------------------------------------- 1 | # Chan's Algorithm 2 | 3 | COMING SOON! 4 | 5 | 8 | 9 | ## License 10 | 11 | ##### Code Examples 12 | 13 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 14 | 15 | ##### Text 16 | 17 | 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). 18 | 19 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 20 | 21 | ##### Pull Requests 22 | 23 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 24 | - none 25 | -------------------------------------------------------------------------------- /contents/computus/res/metonic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/computus/res/metonic.png -------------------------------------------------------------------------------- /contents/computus/res/orbit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/computus/res/orbit.png -------------------------------------------------------------------------------- /contents/computus/res/servois_1800.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/computus/res/servois_1800.png -------------------------------------------------------------------------------- /contents/computus/res/servois_2000.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/computus/res/servois_2000.png -------------------------------------------------------------------------------- /contents/computus/res/synodic_half_year.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/computus/res/synodic_half_year.png -------------------------------------------------------------------------------- /contents/convolutions/convolutional_theorem/code/julia/convolutional_theorem.jl: -------------------------------------------------------------------------------- 1 | using FFTW 2 | using LinearAlgebra 3 | using DelimitedFiles 4 | 5 | # using the convolutional theorem 6 | function convolve_fft(signal1::Array{T}, signal2::Array{T}) where {T <: Number} 7 | return ifft(fft(signal1).*fft(signal2)) 8 | end 9 | 10 | function main() 11 | 12 | # sawtooth functions for x and y 13 | x = [float(i)/200 for i = 1:200] 14 | y = [float(i)/200 for i = 1:200] 15 | 16 | # Normalization is not strictly necessary, but good practice 17 | normalize!(x) 18 | normalize!(y) 19 | 20 | # cyclic convolution via the convolutional theorem 21 | fft_output = convolve_fft(x, y) 22 | 23 | # outputting convolutions to different files for plotting in external code 24 | # note: we are outputting just the real component because the imaginary 25 | # component is virtually 0 26 | writedlm("fft.dat", real(fft_output)) 27 | 28 | end 29 | 30 | main() 31 | -------------------------------------------------------------------------------- /contents/convolutions/convolutional_theorem/code/python/convolutional_theorem.py: -------------------------------------------------------------------------------- 1 | from scipy.fft import fft, ifft 2 | import numpy as np 3 | 4 | # using the convolutional theorem 5 | def convolve_fft(signal1, signal2): 6 | return ifft(np.multiply(fft(signal1),fft(signal2))) 7 | 8 | # Sawtooth functions 9 | x = [float(i)/200 for i in range(1,101)] 10 | y = [float(i)/200 for i in range(1,101)] 11 | 12 | x /= np.linalg.norm(x) 13 | y /= np.linalg.norm(y) 14 | 15 | # Convolving the two signals 16 | fft_output = convolve_fft(x, y) 17 | 18 | np.savetxt("fft.dat", np.real(fft_output)) 19 | 20 | -------------------------------------------------------------------------------- /contents/convolutions/res/1d_gaussian.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/1d_gaussian.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/1d_rand_gaussian_cyclic.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/1d_rand_gaussian_cyclic.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/1d_rand_gaussian_full.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/1d_rand_gaussian_full.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/1d_rand_gaussian_simple.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/1d_rand_gaussian_simple.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/1d_sawtooth.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/1d_sawtooth.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/2d.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/2d.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/circle_blur.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/circle_blur.png -------------------------------------------------------------------------------- /contents/convolutions/res/cyclic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/cyclic.png -------------------------------------------------------------------------------- /contents/convolutions/res/double_gaussian.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/double_gaussian.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/full_linear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/full_linear.png -------------------------------------------------------------------------------- /contents/convolutions/res/heart_8bit.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/heart_8bit.png -------------------------------------------------------------------------------- /contents/convolutions/res/sawtooth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/sawtooth.png -------------------------------------------------------------------------------- /contents/convolutions/res/simple_linear.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/simple_linear.png -------------------------------------------------------------------------------- /contents/convolutions/res/sobel_filters.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/sobel_filters.png -------------------------------------------------------------------------------- /contents/convolutions/res/square_wave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/square_wave.png -------------------------------------------------------------------------------- /contents/convolutions/res/triangle_square_conv.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/triangle_square_conv.mp4 -------------------------------------------------------------------------------- /contents/convolutions/res/triangle_wave.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/convolutions/res/triangle_wave.png -------------------------------------------------------------------------------- /contents/cooley_tukey/code/asm-x64/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.X64(f'#/build/asm-x64/{dirname}', Glob('*.s'), LIBS=['m'], LINKFLAGS='-no-pie') 7 | -------------------------------------------------------------------------------- /contents/cooley_tukey/code/c/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS=['m', 'fftw3']) 7 | -------------------------------------------------------------------------------- /contents/cooley_tukey/code/haskell/fft.hs: -------------------------------------------------------------------------------- 1 | import Data.Complex 2 | import Data.List (partition) 3 | import Data.Map ((!)) 4 | import qualified Data.Map as M 5 | import Data.Ratio 6 | 7 | dft :: [Complex Double] -> [Complex Double] 8 | dft x = matMult dftMat x 9 | where 10 | n = length x 11 | w = exp $ (-2) * pi * (0 :+ 1) / fromIntegral n 12 | dftMat = [[w ^ (j * k) | j <- [0 .. n - 1]] | k <- [0 .. n - 1]] 13 | matMult m x = map (sum . zipWith (*) x) m 14 | 15 | fft :: [Complex Double] -> [Complex Double] 16 | fft x = fft' x 17 | where 18 | n = length x 19 | w0 = exp ((-2) * pi * (0 :+ 1) / fromIntegral n) 20 | w = M.fromList [(k % n, w0 ^ k) | k <- [0 .. n - 1]] 21 | fft' [x] = [x] 22 | fft' x = 23 | let (evens, odds) = partition (even . fst) $ zip [0 ..] x 24 | e = fft' $ map snd evens 25 | o = fft' $ map snd odds 26 | x1 = zipWith3 (\e o k -> e + o * w ! (k %n)) e o [0 ..] 27 | x2 = zipWith3 (\e o k -> e - o * w ! (k %n)) e o [0 ..] 28 | in x1 ++ x2 29 | 30 | main = do 31 | print $ dft [0, 1, 2, 3] 32 | print $ fft [0, 1, 2, 3] 33 | -------------------------------------------------------------------------------- /contents/cooley_tukey/code/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "rust" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | rand = "0.7.3" 10 | rustfft = "4.1.0" 11 | 12 | [[bin]] 13 | path = "./fft.rs" 14 | name = "main" -------------------------------------------------------------------------------- /contents/cooley_tukey/res/FT_example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/FT_example.png -------------------------------------------------------------------------------- /contents/cooley_tukey/res/butterfly_diagram.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/butterfly_diagram.png -------------------------------------------------------------------------------- /contents/cooley_tukey/res/fft.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/fft.png -------------------------------------------------------------------------------- /contents/cooley_tukey/res/radix-2screen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/radix-2screen.jpg -------------------------------------------------------------------------------- /contents/cooley_tukey/res/radix-2screen_positive.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/radix-2screen_positive.jpg -------------------------------------------------------------------------------- /contents/cooley_tukey/res/radix-8screen.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/radix-8screen.jpg -------------------------------------------------------------------------------- /contents/cooley_tukey/res/sinusoid.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/cooley_tukey/res/sinusoid.png -------------------------------------------------------------------------------- /contents/data_structures/data_structures.md: -------------------------------------------------------------------------------- 1 | # Data Structures 2 | 3 | This is a book about algorithms. 4 | The fundamental building blocks of algorithms are data structures, and thus as more algorithms are added to the Archive, more data structures will be added to this section. 5 | 6 | ## License 7 | 8 | ##### Code Examples 9 | 10 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 11 | 12 | ##### Text 13 | 14 | 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). 15 | 16 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 17 | 18 | ##### Pull Requests 19 | 20 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 21 | - none 22 | -------------------------------------------------------------------------------- /contents/differential_equations/differential_equations.md: -------------------------------------------------------------------------------- 1 | # Differential Equations 2 | 3 | Differential equations lie at the heart of many different systems in physics, economics, biology, chemistry, and many other areas of research and engineering. 4 | Here, we discuss many different methods to solve particular sets of differential equations. 5 | 6 | ## License 7 | 8 | ##### Code Examples 9 | 10 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 11 | 12 | ##### Text 13 | 14 | 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). 15 | 16 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 17 | 18 | ##### Pull Requests 19 | 20 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 21 | - none 22 | -------------------------------------------------------------------------------- /contents/domain_coloring/res/absz.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/absz.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/hsv.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/hsv.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/hsv2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/hsv2.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/hsv3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/hsv3.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/hsv4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/hsv4.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/hsv5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/hsv5.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/rgb1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/rgb1.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/rgb2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/rgb2.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/shade.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/shade.png -------------------------------------------------------------------------------- /contents/domain_coloring/res/z2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/domain_coloring/res/z2.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/bash/euclid.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | abs() { 3 | local ret=$1 4 | if (( ret < 0 )); then 5 | ((ret *= -1)) 6 | fi 7 | printf "%s" "$ret" 8 | } 9 | 10 | euclid_mod() { 11 | local a 12 | local b 13 | a=$(abs "$1") 14 | b=$(abs "$2") 15 | 16 | while (( b != 0 )); do 17 | ((tmp = b)) 18 | ((b = a % b)) 19 | ((a = tmp)) 20 | done 21 | printf "%s" "$a" 22 | } 23 | 24 | euclid_sub() { 25 | local a 26 | local b 27 | a=$(abs "$1") 28 | b=$(abs "$2") 29 | 30 | while (( a != b )); do 31 | if (( a > b )); then 32 | ((a -= b)) 33 | else 34 | ((b -= a)) 35 | fi 36 | done 37 | printf "%s" "$a" 38 | } 39 | 40 | result=$(euclid_mod $((64 * 67)) $((64 * 81))) 41 | echo "$result" 42 | result=$(euclid_sub $((128 * 12)) $((128 * 77))) 43 | echo "$result" 44 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/c/euclidean_example.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | int euclid_mod(int a, int b) { 5 | a = abs(a); 6 | b = abs(b); 7 | 8 | while (b != 0) { 9 | int temp = b; 10 | b = a % b; 11 | a = temp; 12 | } 13 | 14 | return a; 15 | } 16 | 17 | int euclid_sub(int a, int b) { 18 | a = abs(a); 19 | b = abs(b); 20 | 21 | while (a != b) { 22 | if (a > b) { 23 | a -= b; 24 | } else { 25 | b -= a; 26 | } 27 | } 28 | 29 | return a; 30 | } 31 | 32 | int main() { 33 | int check1 = euclid_mod(64 * 67, 64 * 81); 34 | int check2 = euclid_sub(128 * 12, 128 * 77); 35 | 36 | printf("%d\n", check1); 37 | printf("%d\n", check2); 38 | 39 | return 0; 40 | } 41 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/clisp/euclidean.lisp: -------------------------------------------------------------------------------- 1 | ;;;; Euclidean algorithm implementation in Common Lisp 2 | 3 | (defun euclid-sub (a b) 4 | "Finds the greatest common divsor for any two integers" 5 | (defun euclid-sub* (a b) 6 | "Finds the greatest common divisor for any two positive integers" 7 | (if (eql a b) 8 | a 9 | (if (> a b) 10 | (euclid-sub* (- a b) b) 11 | (euclid-sub* a (- b a))))) 12 | (euclid-sub* (abs a) (abs b))) 13 | 14 | (defun euclid-mod (a b) 15 | "Finds the greatest common divisor for any two integers" 16 | (if (zerop b) 17 | (abs a) 18 | (euclid-mod b (mod a b)))) 19 | 20 | (print (euclid-sub (* 64 67) (* 64 81))) 21 | (print (euclid-mod (* 128 12) (* 128 77))) 22 | 23 | ;; Quick test 24 | (assert 25 | (eql (euclid-sub (* 64 67) (* 64 81)) 26 | (gcd (* 64 67) (* 64 81)))) 27 | 28 | (assert 29 | (eql (euclid-mod (* 64 67) (* 64 81)) 30 | (gcd (* 64 67) (* 64 81)))) 31 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/clojure/euclidean_example.clj: -------------------------------------------------------------------------------- 1 | ;; earthfail 2 | (defn euclid-sub [a b] 3 | (loop [i (Math/abs a) j (Math/abs b)] 4 | (if (= i j) 5 | i 6 | (if (> i j) 7 | (recur (- i j) j) 8 | (recur i (- j i)))))) 9 | (defn euclid-mod [a b] 10 | (loop [i (Math/abs a) j (Math/abs b)] 11 | (if (zero? j) 12 | i 13 | (recur j (% i j))))) 14 | 15 | (print 16 | (euclid-sub (* 64 67) 17 | (* 64 81)) 18 | (euclid-mod (* 128 12) 19 | (* 128 77))) 20 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/coconut/euclidean.coco: -------------------------------------------------------------------------------- 1 | def euclid_sub(a is int, 0) = a 2 | addpattern def euclid_sub(0, b is int) = b 3 | 4 | addpattern def euclid_sub(a is int, b is int): 5 | if a < b: 6 | return euclid_sub(a, b - a) 7 | elif b < a: 8 | return euclid_sub(a - b, b) 9 | return a 10 | 11 | 12 | def euclid_mod(a is int, 0) = a 13 | addpattern def euclid_mod(0, b is int) = b 14 | 15 | addpattern def euclid_mod(a is int, b is int) = euclid_mod(b, a % b) 16 | 17 | if __name__ == '__main__': 18 | print('Euclidean mod:', euclid_mod(64 * 67, 64 * 81)) 19 | print('Euclidean sub:', euclid_sub(128 * 12, 128 * 77)) 20 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/cpp/euclidean.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | // Euclidean algorithm using modulus 6 | int euclid_mod(int a, int b) { 7 | a = std::abs(a); 8 | b = std::abs(b); 9 | 10 | while (b != 0) { 11 | a = std::exchange(b, a % b); 12 | } 13 | 14 | return a; 15 | } 16 | 17 | // Euclidean algorithm with subtraction 18 | int euclid_sub(int a, int b) { 19 | a = std::abs(a); 20 | b = std::abs(b); 21 | 22 | while (a != b) { 23 | if (a > b) { 24 | a -= b; 25 | } else { 26 | b -= a; 27 | } 28 | } 29 | 30 | return a; 31 | } 32 | 33 | int main() { 34 | auto check1 = euclid_mod(64 * 67, 64 * 81); 35 | auto check2 = euclid_sub(128 * 12, 128 * 77); 36 | 37 | std::cout << check1 << '\n'; 38 | std::cout << check2 << '\n'; 39 | } 40 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/csharp/EuclideanAlgorithm.cs: -------------------------------------------------------------------------------- 1 | // submitted by Julian Schacher (jspp) 2 | using System; 3 | 4 | namespace EuclideanAlgorithm 5 | { 6 | public class EuclideanAlgorithm 7 | { 8 | public int EuclidSub(int a, int b) 9 | { 10 | // Math.Abs for negative number support 11 | a = Math.Abs(a); 12 | b = Math.Abs(b); 13 | 14 | while (a != b) 15 | { 16 | if (a > b) 17 | a = a - b; 18 | else 19 | b = b - a; 20 | } 21 | 22 | return a; 23 | } 24 | 25 | public int EuclidMod(int a, int b) 26 | { 27 | // Math.Abs for negative number support 28 | a = Math.Abs(a); 29 | b = Math.Abs(b); 30 | 31 | while (b != 0) 32 | { 33 | var temp = b; 34 | b = a % b; 35 | a = temp; 36 | } 37 | 38 | return a; 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/csharp/Program.cs: -------------------------------------------------------------------------------- 1 | // submitted by Julian Schacher (jspp) 2 | using System; 3 | 4 | namespace EuclideanAlgorithm 5 | { 6 | class Program 7 | { 8 | static void Main(string[] args) 9 | { 10 | Console.WriteLine("EuclideanAlgorithm"); 11 | var euclideanAlgorithm = new EuclideanAlgorithm(); 12 | int check = euclideanAlgorithm.EuclidMod(64 * 67, 64 * 81); 13 | int check2 = euclideanAlgorithm.EuclidSub(128 * 12, 128 * 77); 14 | 15 | Console.WriteLine(check); 16 | Console.WriteLine(check2); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/d/euclidean_algorithm.d: -------------------------------------------------------------------------------- 1 | import std.stdio; 2 | import std.math; 3 | 4 | // Euclidean algorithm using modulus 5 | int euclid_mod(int a, int b) { 6 | int tmp; 7 | a = abs(a); 8 | b = abs(b); 9 | 10 | while (b != 0) { 11 | tmp = a % b; 12 | a = b; 13 | b = tmp; 14 | } 15 | 16 | return a; 17 | } 18 | 19 | // Euclidean algorithm with subtraction 20 | int euclid_sub(int a, int b) { 21 | a = abs(a); 22 | b = abs(b); 23 | 24 | while (a != b) { 25 | if (a > b) { 26 | a -= b; 27 | } else { 28 | b -= a; 29 | } 30 | } 31 | 32 | return a; 33 | } 34 | 35 | void main() 36 | { 37 | auto check1 = euclid_mod(64 * 67, 64 * 81); 38 | auto check2 = euclid_sub(128 * 12, 128 * 77); 39 | 40 | writeln("Modulus-based euclidean algorithm result: ", check1); 41 | writeln("Subtraction-based euclidean algorithm result: ", check2); 42 | } 43 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/emojicode/euclidean_algorithm.emojic: -------------------------------------------------------------------------------- 1 | 🐇 ⬆️ 🍇 2 | 🐇 ❗️ 🔼 a 🔢 b 🔢 ➡️ 🔢 🍇 3 | 💭 Use 🏧 (returns the absolute value) to support negative numbers. 4 | 🏧a ❗️ ➡️ 🖍🆕var_a 5 | 🏧b ❗️ ➡️ 🖍🆕var_b 6 | 7 | ️🔁 ❎ var_a 🙌 var_b ❗️ 🍇 8 | ↪️ var_a ▶️ var_b 🍇 9 | var_a ⬅️ ➖ var_b 10 | 🍉 11 | 🙅 🍇 12 | var_b ⬅️ ➖ var_a 13 | 🍉 14 | 🍉 15 | 16 | ↩️ var_a 17 | 🍉 18 | 19 | 🐇 ❗️ ⏫ a 🔢 b 🔢 ➡️ 🔢 🍇 20 | 💭 Use 🏧 (returns the absolute value) to support negative numbers. 21 | 🏧a ❗️ ➡️ 🖍🆕var_a 22 | 🏧b ❗️ ➡️ 🖍🆕var_b 23 | 24 | ️🔁 ❎ var_b 🙌 0 ❗️ 🍇 25 | var_b ➡️ temp 26 | var_a 🚮 var_b ➡️ 🖍var_b 27 | temp ➡️ 🖍var_a 28 | 🍉 29 | 30 | ↩️ var_a 31 | 🍉 32 | 🍉 33 | 34 | 🏁 🍇 35 | 😀 🔡 ️🔼🐇⬆️ 🤜64 ✖️ 67🤛 🤜64 ✖️ 81🤛 ❗️ 10 ❗️❗️ 36 | 😀 🔡 ️⏫🐇⬆️ 🤜128 ✖️ 12🤛 🤜128 ✖️ 77🤛 ❗️ 10 ❗️❗️ 37 | 🍉 38 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/factor/euclid.factor: -------------------------------------------------------------------------------- 1 | : euclid- ( a b -- gcd ) 2 | [ abs ] bi@ 3 | [ 2dup = ] 4 | [ 5 | ! make sure the lower number is deeper 6 | 2dup >= [ swap ] when 7 | over - 8 | ! leaves us with stack { } 9 | ] 10 | until 11 | ! we have the GCD twice now, drop one 12 | drop 13 | ; 14 | 15 | : euclid% ( a b -- gcd ) 16 | [ abs ] bi@ ! take both absolute values 17 | [ dup zero? ] ! check if `b` (on top) is 0 18 | [ 19 | ! a b -> a b b -> b a b -> b a%b 20 | dup -rot mod 21 | ] 22 | until 23 | ! the zero is on top, so get rid of it 24 | drop 25 | ; 26 | 27 | 42 56 euclid% . ! 14 28 | 48 180 euclid% . ! 12 29 | 30 | 42 56 euclid- . ! 14 31 | 48 180 euclid- . ! 12 32 | 33 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/fortran/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.Fortran(f'#/build/fortran/{dirname}', 'euclidean.f90') 7 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/fortran/euclidean.f90: -------------------------------------------------------------------------------- 1 | INTEGER FUNCTION euclid_sub(a, b) 2 | IMPLICIT NONE 3 | INTEGER, INTENT(INOUT) :: a, b 4 | 5 | a = ABS(a) 6 | b = ABS(b) 7 | 8 | DO WHILE (a /= b) 9 | 10 | IF (a > b) THEN 11 | a = a - b 12 | ELSE 13 | b = b - a 14 | END IF 15 | END DO 16 | 17 | euclid_sub = a 18 | 19 | END FUNCTION euclid_sub 20 | 21 | INTEGER FUNCTION euclid_mod(a, b) 22 | IMPLICIT NONE 23 | INTEGER, INTENT(INOUT) :: a, b 24 | INTEGER :: temp 25 | 26 | DO WHILE (b > 0) 27 | temp = b 28 | b = MODULO(a,b) 29 | a = temp 30 | END DO 31 | 32 | euclid_mod = a 33 | 34 | END FUNCTION euclid_mod 35 | 36 | PROGRAM euclidean 37 | 38 | IMPLICIT NONE 39 | INTEGER :: a, b, euclid_sub, euclid_mod 40 | 41 | a = 24 42 | b = 27 43 | WRITE(*,*) 'Subtraction method: GCD is: ', euclid_sub(a, b) 44 | 45 | a = 24 46 | b = 27 47 | WRITE(*,*) 'Modulus method: GCD is: ', euclid_mod(a, b) 48 | 49 | END PROGRAM euclidean 50 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/go/euclidean.go: -------------------------------------------------------------------------------- 1 | // Submitted by Chinmaya Mahesh (chin123) 2 | 3 | package main 4 | 5 | import "fmt" 6 | 7 | func abs(a int) int { 8 | if a < 0 { 9 | a = -a 10 | } 11 | return a 12 | } 13 | 14 | func euclidMod(a, b int) int { 15 | a = abs(a) 16 | b = abs(b) 17 | 18 | for b != 0 { 19 | a, b = b, a%b 20 | } 21 | 22 | return a 23 | } 24 | 25 | func euclidSub(a, b int) int { 26 | a = abs(a) 27 | b = abs(b) 28 | 29 | for a != b { 30 | if a > b { 31 | a -= b 32 | } else { 33 | b -= a 34 | } 35 | } 36 | 37 | return a 38 | } 39 | 40 | func main() { 41 | check1 := euclidMod(64*67, 64*81) 42 | check2 := euclidSub(128*12, 128*77) 43 | 44 | fmt.Println(check1) 45 | fmt.Println(check2) 46 | } 47 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/haskell/euclidean_algorithm.hs: -------------------------------------------------------------------------------- 1 | -- Method 1: Euclid's original subtraction algorithm 2 | 3 | euclidSub :: Integer -> Integer -> Integer 4 | euclidSub a b = inner (abs a) (abs b) 5 | where 6 | inner x y 7 | -- if a = b, then the gcd is a 8 | | x == y = x 9 | -- if a < b: Recursively call euclidSub with the a and (b-a) as new inputs 10 | | x < y = euclidSub x (y - x) 11 | -- otherwise: Recursively call euclidSub with the a and (b-a) as new inputs 12 | | otherwise = euclidSub (x - y) y 13 | 14 | -- _______________________________________________________________________ 15 | 16 | -- Method 2: Modern implemetation - The modulus method. 17 | 18 | euclidMod :: Integer -> Integer -> Integer 19 | euclidMod a b = inner (abs a) (abs b) 20 | where 21 | -- if a divides b, then gcd is a 22 | inner x 0 = x 23 | -- otherwise, recursively call inner with b and (a mod b) as new inputs 24 | inner x y = inner y (x `mod` y) 25 | 26 | -- _________________________________________________________________________ 27 | 28 | -- Examples 29 | 30 | main :: IO () 31 | main = do 32 | let chk1 = euclidMod (64 * 67) (64 * 81) 33 | chk2 = euclidSub (128 * 12) (128 * 77) 34 | print chk1 35 | print chk2 36 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/java/EuclideanAlgo.java: -------------------------------------------------------------------------------- 1 | // submitted by lolatomroflsinnlos, modified by xam4lor 2 | public class EuclideanAlgo { 3 | public static int euclidSub(int a, int b) { 4 | a = Math.abs(a); 5 | b = Math.abs(b); 6 | 7 | while (a != b) { 8 | if (a > b) { 9 | a -= b; 10 | } else { 11 | b -= a; 12 | } 13 | } 14 | 15 | return a; 16 | } 17 | 18 | public static int euclidMod(int a, int b) { 19 | while (b != 0) { 20 | int tmp = b; 21 | b = a % b; 22 | a = tmp; 23 | } 24 | 25 | return a; 26 | } 27 | 28 | public static void main(String[] args) { 29 | System.out.println(euclidMod(64 * 67, 64 * 81)); 30 | System.out.println(euclidSub(128 * 12, 128 * 77)); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/javascript/euclidean_example.js: -------------------------------------------------------------------------------- 1 | function euclidMod(a, b) { 2 | a = Math.abs(a); 3 | b = Math.abs(b); 4 | 5 | let temp; 6 | while (b !== 0) { 7 | temp = b; 8 | b = a % b; 9 | a = temp; 10 | } 11 | 12 | return a; 13 | } 14 | 15 | function euclidSub(a, b) { 16 | a = Math.abs(a); 17 | b = Math.abs(b); 18 | 19 | while (a !== b) { 20 | if (a > b) { 21 | a -= a - b; 22 | } else { 23 | b = b - a; 24 | } 25 | } 26 | 27 | return a; 28 | } 29 | 30 | console.log(euclidMod(64 * 67, 64 * 81)); 31 | console.log(euclidSub(128 * 12, 128 * 77)); 32 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/julia/euclidean.jl: -------------------------------------------------------------------------------- 1 | function euclid_mod(a::Int64, b::Int64) 2 | a = abs(a) 3 | b = abs(b) 4 | 5 | while(b != 0) 6 | b,a = a%b,b 7 | end 8 | 9 | return a 10 | end 11 | 12 | function euclid_sub(a::Int64, b::Int64) 13 | a = abs(a) 14 | b = abs(b) 15 | 16 | while (a != b) 17 | if (a > b) 18 | a -= b 19 | else 20 | b -= a 21 | end 22 | end 23 | 24 | return a 25 | end 26 | 27 | function main() 28 | check1 = euclid_mod(64 * 67, 64 * 81); 29 | check2 = euclid_sub(128 * 12, 128 * 77); 30 | 31 | println("Modulus-based euclidean algorithm result: $(check1)") 32 | println("subtraction-based euclidean algorithm result: $(check2)") 33 | 34 | end 35 | 36 | main() 37 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/kotlin/Euclidean.kt: -------------------------------------------------------------------------------- 1 | import kotlin.math.absoluteValue 2 | 3 | fun euclidSub(a: Int, b: Int): Int { 4 | var a = a.absoluteValue 5 | var b = b.absoluteValue 6 | 7 | while (a != b) { 8 | if (a > b) a -= b 9 | else b -= a 10 | } 11 | 12 | return a 13 | } 14 | 15 | fun euclidMod(a: Int, b: Int): Int { 16 | var a = a.absoluteValue 17 | var b = b.absoluteValue 18 | 19 | while (b != 0) { 20 | val tmp = b 21 | b = a % b 22 | a = tmp 23 | } 24 | 25 | return a 26 | } 27 | 28 | fun main(args: Array) { 29 | println(euclidSub(128 * 12, 128 * 77)) 30 | println(euclidMod(64 * 67, 64 * 81)) 31 | } 32 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/lua/euclidean.lua: -------------------------------------------------------------------------------- 1 | local function euclid_sub(a, b) 2 | a = math.abs(a) 3 | b = math.abs(b) 4 | 5 | while a ~= b do 6 | if a > b then 7 | a = a-b 8 | else 9 | b = b-a 10 | end 11 | end 12 | 13 | return a 14 | end 15 | 16 | local function euclid_mod(a, b) 17 | a = math.abs(a) 18 | b = math.abs(b) 19 | 20 | while b ~= 0 do 21 | a, b = b, a%b 22 | end 23 | 24 | return a 25 | end 26 | 27 | local function main() 28 | print(euclid_sub(128 * 12, 128 * 77)) 29 | print(euclid_mod(64 * 67, 64 * 81)) 30 | end 31 | 32 | main() 33 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/matlab/euclidean.m: -------------------------------------------------------------------------------- 1 | // Submitted by Max Weinstein 2 | 3 | function gcd = euclidSub(a,b) 4 | 5 | a = abs(a); 6 | b = abs(b); 7 | 8 | while a ~= b 9 | if a > b 10 | a = a - b; 11 | else 12 | b = b - a; 13 | end 14 | end 15 | 16 | gcd = a; 17 | end 18 | 19 | function gcd = euclidMod(a,b) 20 | 21 | a=abs(a); 22 | b=abs(b); 23 | 24 | while b > 0 25 | temp = b; 26 | b = mod(a,b); 27 | a = temp; 28 | end 29 | 30 | gcd = a; 31 | end 32 | 33 | function euclid() 34 | ['gcd(520,420) via euclidSub: ',num2str(euclidSub(520,420))] 35 | ['gcd(183,244) via euclidMod: ',num2str(euclidMod(183,244))] 36 | end -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/nim/euclid_algorithm.nim: -------------------------------------------------------------------------------- 1 | func euclid_mod(in1, in2: int): int = 2 | var 3 | a = abs(in1) 4 | b = abs(in2) 5 | 6 | while b != 0: 7 | let temp: int = b 8 | b = a mod b 9 | a = temp; 10 | 11 | result = a 12 | 13 | func euclid_sub(in1, in2: int): int = 14 | var 15 | a = abs(in1) 16 | b = abs(in2) 17 | 18 | while a != b: 19 | if a > b: 20 | a -= b 21 | else: 22 | b -= a 23 | 24 | result = a 25 | 26 | when isMainModule: 27 | echo euclid_sub(64 * 67, 64 * 81) 28 | echo euclid_mod(128 * 12, 128 * 77) 29 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/ocaml/euclidean_example.ml: -------------------------------------------------------------------------------- 1 | (* contributed by Nicole Mazzuca (ubsan) *) 2 | 3 | let euclid_mod a b = 4 | let rec inner a = function 5 | | 0 -> a 6 | | b -> inner b (a mod b) 7 | in (inner (abs a) (abs b)) 8 | 9 | let euclid_sub a b = 10 | let rec inner a b = 11 | if a = b then 12 | a 13 | else if a < b then 14 | inner a (b - a) 15 | else 16 | inner (a - b) b 17 | in (inner (abs a) (abs b)) 18 | 19 | let chk1 = euclid_mod (64 * 67) (64 * 81) 20 | let chk2 = euclid_sub (128 * 12) (128 * 77) 21 | let () = 22 | chk1 |> print_int |> print_newline; 23 | chk2 |> print_int |> print_newline 24 | 25 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/php/euclidean.php: -------------------------------------------------------------------------------- 1 | $b) { 11 | $a = $a - $b; 12 | } else { 13 | $b = $b - $a; 14 | } 15 | } 16 | 17 | return $a; 18 | } 19 | 20 | function euclid_mod(int $a, int $b): int 21 | { 22 | $a = abs($a); 23 | $b = abs($b); 24 | 25 | while ($b !== 0) { 26 | list($b, $a) = [$a % $b, $b]; 27 | } 28 | 29 | return $a; 30 | } 31 | 32 | printf('Euclidean mod: %s', euclid_mod(64 * 67, 64 * 81)); 33 | echo PHP_EOL; 34 | printf('Euclidean sub: %s', euclid_sub(128 * 12, 128 * 77)); 35 | echo PHP_EOL; 36 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/piet/mod/euclidian_algorithm_mod.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/code/piet/mod/euclidian_algorithm_mod.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/piet/mod/euclidian_algorithm_mod_large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/code/piet/mod/euclidian_algorithm_mod_large.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/piet/subtract/euclidian_algorithm_subtract.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/code/piet/subtract/euclidian_algorithm_subtract.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/piet/subtract/euclidian_algorithm_subtract_large.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/code/piet/subtract/euclidian_algorithm_subtract_large.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/powershell/euclidean_algorithm.ps1: -------------------------------------------------------------------------------- 1 | function Sub-Euclid($a, $b) { 2 | $a = [Math]::Abs($a) 3 | $b = [Math]::Abs($b) 4 | 5 | while ($a -ne $b) { 6 | if ($a -gt $b) { 7 | $a = $a - $b 8 | } else { 9 | $b = $b - $a 10 | } 11 | } 12 | 13 | return $a 14 | } 15 | 16 | function Mod-Euclid($a, $b) { 17 | $a = [Math]::Abs($a) 18 | $b = [Math]::Abs($b) 19 | 20 | while ($b -ne 0) { 21 | $tmp = $b 22 | $b = $a % $b 23 | $a = $tmp 24 | } 25 | 26 | return $a 27 | } 28 | 29 | Write-Host "Subtraction-based euclidean algorithm result: $(Mod-Euclid $(64 * 67) $(64 * 81))" 30 | Write-Host "Modulus-based euclidean algorithm result: $(Sub-Euclid $(128 * 12) $(128 * 77))" 31 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/python/euclidean_example.py: -------------------------------------------------------------------------------- 1 | def euclid_mod(a, b): 2 | 3 | a = abs(a) 4 | b = abs(b) 5 | 6 | while b > 0: 7 | a, b = b, a % b 8 | 9 | return a 10 | 11 | def euclid_sub(a, b): 12 | 13 | a = abs(a) 14 | b = abs(b) 15 | 16 | if a == 0: 17 | return b 18 | elif b == 0: 19 | return a 20 | 21 | while a != b: 22 | if a > b: 23 | a -= b 24 | else: 25 | b -= a 26 | 27 | return a 28 | 29 | if __name__=="__main__": 30 | print('Euclidean mod: ', euclid_mod(64 * 67, 64 * 81)) 31 | print('Euclidean sub: ', euclid_sub(128 * 12, 128 * 77)) 32 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/racket/euclidean_algorithm.rkt: -------------------------------------------------------------------------------- 1 | #lang racket 2 | 3 | (define (euclid_sub a b) 4 | (local ((define (euclid_sub* x y) 5 | (if (= x y) 6 | x 7 | (if (> x y) 8 | (euclid_sub* (- x y) y) 9 | (euclid_sub* x (- y x)) 10 | ) 11 | ) 12 | )) (euclid_sub* (abs a) (abs b)) 13 | ) 14 | ) 15 | 16 | (define (euclid_mod a b) 17 | (local ((define (euclid_mod* a b) 18 | (if (= 0 b) 19 | (abs a) 20 | (euclid_mod* b (modulo a b)) 21 | ) 22 | )) (euclid_mod* a b) 23 | ) 24 | ) 25 | 26 | (displayln (euclid_sub (* 64 67) (* 64 81))) 27 | (displayln (euclid_mod (* 128 12) (* 128 77))) 28 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/ruby/euclidean.rb: -------------------------------------------------------------------------------- 1 | def gcd_mod(a, b) 2 | a = a.abs 3 | b = b.abs 4 | a, b = b, a%b until b.zero? 5 | a 6 | end 7 | 8 | def gcd_minus(a, b) 9 | a = a.abs 10 | b = b.abs 11 | until a == b 12 | if a > b 13 | a -= b 14 | else 15 | b -= a 16 | end 17 | end 18 | a 19 | end 20 | 21 | p gcd_mod(12 * 6, 12 * 4) #=> 12 22 | p gcd_mod(9 * 667, 9 * 104) #=> 9 23 | 24 | p gcd_minus(12 * 6, 12 * 4) #=> 12 25 | p gcd_minus(9 * 667, 9 * 104) #=> 9 26 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/rust/euclidean_example.rs: -------------------------------------------------------------------------------- 1 | // contributed by Nicole Mazzuca (ubsan) 2 | 3 | fn euclid_sub(mut a: i64, mut b: i64) -> i64 { 4 | a = a.abs(); 5 | b = b.abs(); 6 | while a != b { 7 | if a < b { 8 | b -= a; 9 | } else { 10 | a -= b; 11 | } 12 | } 13 | 14 | a 15 | } 16 | 17 | fn euclid_rem(mut a: i64, mut b: i64) -> i64 { 18 | a = a.abs(); 19 | b = b.abs(); 20 | while b != 0 { 21 | let tmp = b; 22 | b = a % b; 23 | a = tmp; 24 | } 25 | 26 | a 27 | } 28 | 29 | fn main() { 30 | let chk1 = euclid_rem(64 * 67, 64 * 81); 31 | let chk2 = euclid_sub(128 * 12, 128 * 77); 32 | println!("{}", chk1); 33 | println!("{}", chk2); 34 | } 35 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/scala/euclidean.scala: -------------------------------------------------------------------------------- 1 | object Euclid { 2 | 3 | def euclid_sub(a: Int, b: Int): Int = 4 | (Math.abs(a), Math.abs(b)) match { 5 | case (0, _) | (_, 0) => 0 6 | case (x, y) if x < y => euclid(x, y - x) 7 | case (x, y) if x > y => euclid(x - y, y) 8 | case _ => a 9 | } 10 | 11 | def euclid_mod(a: Int, b: Int): Int = 12 | (Math.abs(a), Math.abs(b)) match { 13 | case (_, 0) => a 14 | case (a, b) => euclid_mod(b, a % b) 15 | } 16 | 17 | def main(args: Array[String]): Unit = { 18 | println(euclid_sub(151 * 899, 151 * 182)) 19 | println(euclid_mod(151 * 899, 151 * 182)) 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/scheme/euclidalg.ss: -------------------------------------------------------------------------------- 1 | (define (euclid-sub a b) 2 | (cond 3 | [(or (negative? a)(negative? b))(euclid-sub (abs a)(abs b))] 4 | [(eq? a b) a] 5 | [(> a b)(euclid-sub(- a b) b)] 6 | [else 7 | (euclid-sub a (- b a))])) 8 | 9 | (define (euclid-mod a b) 10 | (if (zero? b) 11 | a 12 | (euclid-mod b (modulo a b)))) 13 | 14 | (display (euclid-mod (* 64 67) (* 64 81))) (newline) 15 | (display (euclid-sub (* 128 12) (* 128 77))) (newline) 16 | 17 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/scratch/euclidean.txt: -------------------------------------------------------------------------------- 1 | define euclid_sub 2 | set [a v] to ([abs v] of [a v]) 3 | set [b v] to ([abs v] of [b v]) 4 | repeat until <(a) = (b)> 5 | if <(a) > (b)> then 6 | set [a v] to ((a) - (b)) 7 | else 8 | set [b v] to ((b) - (a)) 9 | 10 | 11 | define euclid_mod 12 | set [a v] to ([abs v] of [a v]) 13 | set [b v] to ([abs v] of [b v]) 14 | repeat until <(b) = (0)> 15 | set [temp v] to (b) 16 | set [b v] to ((a) mod (b)) 17 | set [a v] to (temp) 18 | 19 | when green flag clicked 20 | set [a v] to ((64) * (67)) 21 | set [b v] to ((64) * (81)) 22 | euclid_sub 23 | set [a v] to ((128) * (12)) 24 | set [b v] to ((128) * (77)) 25 | euclid_mod 26 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/smalltalk/euclid.st: -------------------------------------------------------------------------------- 1 | Integer>>euclidSub: secondNumber 2 | "Euclidean algorithm with subtraction" 3 | | a b | 4 | a := self abs. 5 | b := secondNumber abs. 6 | [ a == b ] whileFalse: [ 7 | a > b ifTrue: [ 8 | a := a - b. 9 | ] ifFalse: [ 10 | b := b - a. 11 | ]. 12 | ]. 13 | ^a. 14 | 15 | Integer>>euclidMod: secondNumber 16 | "Euclidean algorithm with modulus." 17 | | a b oldB | 18 | a := self abs. 19 | b := secondNumber abs. 20 | [ b == 0 ] whileFalse: [ 21 | oldB := b. 22 | b := a % b. 23 | a := oldB. 24 | ]. 25 | ^a. 26 | 27 | Transcript show: ((64 * 67) euclidSub: (64 * 81)). 28 | Transcript cr. 29 | Transcript show: ((128 * 12) euclidMod: (128 * 77)). 30 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/swift/euclidean_algorithm.swift: -------------------------------------------------------------------------------- 1 | func euclidSub(a: Int, b: Int) -> Int { 2 | var a = abs(a) 3 | var b = abs(b) 4 | 5 | while (a != b) { 6 | if (a > b) { 7 | a -= b 8 | } else { 9 | b -= a 10 | } 11 | } 12 | 13 | return a 14 | } 15 | 16 | func euclidMod(a: Int, b: Int) -> Int { 17 | var a = abs(a); 18 | var b = abs(b); 19 | 20 | while (b != 0) { 21 | let temp = b 22 | b = a % b 23 | a = temp 24 | } 25 | 26 | return a 27 | } 28 | 29 | func main() { 30 | print(euclidMod(a: 64 * 67, b: 64 * 81)) 31 | print(euclidSub(a: 128 * 12, b: 128 * 77)) 32 | } 33 | 34 | main() 35 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/viml/euclidean.vim: -------------------------------------------------------------------------------- 1 | function s:euclid_mod(a, b) 2 | let l:a = abs(a:a) 3 | let l:b = abs(a:b) 4 | 5 | while l:b != 0 6 | let l:c = l:b 7 | let l:b = l:a % l:b 8 | let l:a = l:c 9 | endwhile 10 | 11 | return l:a 12 | endfunction 13 | 14 | function s:euclid_sub(a, b) 15 | let l:a = abs(a:a) 16 | let l:b = abs(a:b) 17 | 18 | while l:a != l:b 19 | if l:a > l:b 20 | let l:a -= l:b 21 | else 22 | let l:b -= l:a 23 | endif 24 | endwhile 25 | 26 | return l:a 27 | endfunction 28 | 29 | let s:check_1 = s:euclid_mod(64 * 67, 64 * 71) 30 | let s:check_2 = s:euclid_sub(128 * 12, 128 * 77) 31 | 32 | echo 'Modulus-based euclidean algorithm result:' s:check_1 33 | echo 'subtraction-based euclidean algorithm result:' s:check_2 34 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/whitespace/euclidian_mod.ws: -------------------------------------------------------------------------------- 1 | Euclidian algorithm modulo method. 2 | Enter two positive integers. 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | The 28 | end. 29 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/whitespace/euclidian_mod_comments.ws: -------------------------------------------------------------------------------- 1 | Reading the input: a, b 2 | [SPACE][SPACE][SPACE][LF] push 0 3 | [SPACE][SPACE][SPACE][TAB][LF] push 1 4 | [TAB][LF][TAB][TAB] readi 5 | [TAB][LF][TAB][TAB] readi 6 | 7 | Loop: a, b => b, a%b 8 | [LF][SPACE][SPACE][LF] label_0: 9 | [SPACE][SPACE][SPACE][LF] push 0 10 | [TAB][TAB][TAB] retrieve 11 | [SPACE][LF][SPACE] dup 12 | [LF][TAB][SPACE][TAB][LF] jmp zero label_1 13 | [SPACE][SPACE][SPACE][TAB][LF] push 1 14 | [TAB][TAB][TAB] retrieve 15 | [SPACE][LF][TAB] swap 16 | [TAB][SPACE][TAB][TAB] mod 17 | [SPACE][SPACE][SPACE][LF] push 0 18 | [TAB][TAB][TAB] retrieve 19 | [SPACE][SPACE][SPACE][TAB][LF] push 1 20 | [SPACE][LF][TAB] swap 21 | [TAB][TAB][SPACE] store 22 | [SPACE][SPACE][SPACE][LF] push 0 23 | [SPACE][LF][TAB] swap 24 | [TAB][TAB][SPACE] store 25 | [LF][SPACE][LF][LF] jmp label_0 26 | 27 | Exit when b=0 28 | [LF][SPACE][SPACE][TAB][LF] label_1: 29 | [SPACE][SPACE][SPACE][TAB][LF] push 1 30 | [TAB][TAB][TAB] retrieve 31 | [TAB][LF][SPACE][TAB] printi 32 | [LF][LF][LF][LF] end 33 | -------------------------------------------------------------------------------- /contents/euclidean_algorithm/code/whitespace/euclidian_sub.ws: -------------------------------------------------------------------------------- 1 | Euclidian algorithm subtraction method. 2 | Enter two positive integers. 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | The 36 | end. -------------------------------------------------------------------------------- /contents/euclidean_algorithm/res/modulus.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/res/modulus.png -------------------------------------------------------------------------------- /contents/euclidean_algorithm/res/subtraction.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/euclidean_algorithm/res/subtraction.png -------------------------------------------------------------------------------- /contents/flood_fill/res/example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/example.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_1.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_2.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_3.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_4.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_5.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_5.png -------------------------------------------------------------------------------- /contents/flood_fill/res/grid_6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/grid_6.png -------------------------------------------------------------------------------- /contents/flood_fill/res/queue_animation.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/queue_animation.mp4 -------------------------------------------------------------------------------- /contents/flood_fill/res/recurse_animation.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/recurse_animation.mp4 -------------------------------------------------------------------------------- /contents/flood_fill/res/simple_circle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/flood_fill/res/simple_circle.png -------------------------------------------------------------------------------- /contents/fortran/fortran.md: -------------------------------------------------------------------------------- 1 | # FORTRAN 2 | 3 | Alright, so here's the thing about Fortran. It's old. 4 | 5 | ## License 6 | 7 | ##### Code Examples 8 | 9 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 10 | 11 | ##### Text 12 | 13 | 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). 14 | 15 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 16 | 17 | ##### Pull Requests 18 | 19 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 20 | - none 21 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/asm-x64/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.X64(f'#/build/asm-x64/{dirname}', Glob('*.s'), LIBS='m', LINKFLAGS='-no-pie') 7 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/c/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') 7 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/c/euler.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void solve_euler(double timestep, double *result, size_t n) { 5 | if (n != 0) { 6 | result[0] = 1; 7 | for (size_t i = 1; i < n; ++i) { 8 | result[i] = result[i-1] - 3.0 * result[i-1] * timestep; 9 | } 10 | } 11 | } 12 | 13 | int check_result(double *result, size_t n, double threshold, double timestep) { 14 | int is_approx = 1; 15 | for (size_t i = 0; i < n; ++i) { 16 | double solution = exp(-3.0 * i * timestep); 17 | if (fabs(result[i] - solution) > threshold) { 18 | printf("%f %f\n", result[i], solution); 19 | is_approx = 0; 20 | } 21 | } 22 | 23 | return is_approx; 24 | } 25 | 26 | int main() { 27 | double result[100]; 28 | double threshold = 0.01; 29 | double timestep = 0.01; 30 | 31 | solve_euler(timestep, result, 100); 32 | printf("%d\n", check_result(result, 100, threshold, timestep)); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/clisp/euler.lisp: -------------------------------------------------------------------------------- 1 | ;;;; Forward euler implementation in Common Lisp 2 | 3 | (defun solve-euler (timestep n) 4 | "Returns a function where y'(t) = -3t and y(0) = 0 using the forward euler method" 5 | (loop 6 | with result = (make-array n :initial-element 1) 7 | for i from 1 upto (1- n) do 8 | (setf (svref result i) (- (svref result (1- i)) (* 3 (svref result (1- i)) timestep))) 9 | finally (return result))) 10 | 11 | (defun approximatep (result threshold timestep) 12 | "Checks the result from the solve-euler function" 13 | (loop 14 | with approximatep = t 15 | with solution = 0 16 | for i from 0 upto (1- (length result)) do 17 | (setf solution (exp (* (- 3) i timestep))) 18 | (when (> (- (svref result i) solution) threshold) 19 | (setf approximatep nil) 20 | (format t "~d ~d~%" (svref result i) solution)) 21 | finally (return approximatep))) 22 | 23 | (defvar timestep 0.01) 24 | (defvar n 100) ; number of steps 25 | (defvar threshold 0.01) 26 | 27 | (defvar result (solve-euler timestep n)) 28 | (defvar approximatep (approximatep result threshold timestep)) 29 | (format t "~:[Value(s) not in threshold~;All values within threshold~]~%" approximatep) 30 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/elm/elm.json: -------------------------------------------------------------------------------- 1 | { 2 | "type": "application", 3 | "source-directories": [ 4 | "src" 5 | ], 6 | "elm-version": "0.19.1", 7 | "dependencies": { 8 | "direct": { 9 | "bemyak/elm-slider": "1.0.0", 10 | "elm/browser": "1.0.2", 11 | "elm/core": "1.0.5", 12 | "elm/html": "1.0.0", 13 | "elm/json": "1.1.3", 14 | "elm/svg": "1.0.1", 15 | "elm/time": "1.0.0", 16 | "rtfeldman/elm-hex": "1.0.0" 17 | }, 18 | "indirect": { 19 | "debois/elm-dom": "1.3.0", 20 | "elm/url": "1.0.0", 21 | "elm/virtual-dom": "1.0.2" 22 | } 23 | }, 24 | "test-dependencies": { 25 | "direct": {}, 26 | "indirect": {} 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/go/euler.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "math" 6 | ) 7 | 8 | func forwardEuler(timeStep float64, n int) []float64 { 9 | result := make([]float64, n) 10 | result[0] = 1 11 | for x := 1; x < n; x++ { 12 | result[x] = result[x-1] - 3*result[x-1]*timeStep 13 | } 14 | return result 15 | } 16 | 17 | func check(result []float64, threshold, timeStep float64) bool { 18 | approx := true 19 | for x := 0.; int(x) < len(result); x++ { 20 | solution := math.Exp(-3. * x * timeStep) 21 | if math.Abs(result[int(x)]-solution) > threshold { 22 | fmt.Println(result[int(x)], solution) 23 | approx = false 24 | } 25 | } 26 | return approx 27 | } 28 | 29 | func main() { 30 | timeStep, threshold := .01, .01 31 | n := 100 32 | 33 | result := forwardEuler(timeStep, n) 34 | if check(result, threshold, timeStep) { 35 | fmt.Println("All values within threshold") 36 | } else { 37 | fmt.Println("Value(s) not within threshold") 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/haskell/euler.hs: -------------------------------------------------------------------------------- 1 | solveEuler :: Num a => (a -> a) -> a -> a -> [a] 2 | solveEuler f ts = iterate (\x -> x + f x * ts) 3 | 4 | checkResult :: (Ord a, Num a, Num t, Enum t) => a -> (t -> a) -> [a] -> Bool 5 | checkResult thresh check = 6 | and . zipWith (\i k -> abs (check i - k) < thresh) [0..] 7 | 8 | kinematics :: Double -> Double 9 | kinematics x = -3 * x 10 | 11 | main :: IO () 12 | main = 13 | let timestep = 0.01 14 | n = 100 15 | threshold = 0.01 16 | checkResult' = checkResult threshold $ exp . (\x -> -3 * x * timestep) 17 | in putStrLn $ 18 | if checkResult' (take n $ solveEuler kinematics timestep 1) 19 | then "All values within threshold" 20 | else "Value(s) not in threshold" 21 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/javascript/euler.js: -------------------------------------------------------------------------------- 1 | function forwardEuler(timeStep, n) { 2 | const arr = [1]; 3 | for (let i = 1; i <= n; i++) { 4 | arr[i] = arr[i - 1] - 3 * arr[i - 1] * timeStep; 5 | } 6 | return arr; 7 | } 8 | 9 | function checkEuler(arr, timeStep, threshold) { 10 | let isApprox = true; 11 | arr.forEach((_value, i) => { 12 | const solution = Math.exp(-3 * timeStep * i); 13 | 14 | if (Math.abs(arr[i] - solution) > threshold) { 15 | console.log(arr[i], solution); 16 | isApprox = false; 17 | } 18 | }); 19 | return isApprox; 20 | } 21 | 22 | function main() { 23 | const timeStep = 0.01; 24 | const threshold = 0.01; 25 | const n = 100; 26 | const eulerResult = forwardEuler(timeStep, n); 27 | const checkResult = checkEuler(eulerResult, timeStep, threshold); 28 | console.log(checkResult); 29 | } 30 | 31 | main(); 32 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/julia/euler.jl: -------------------------------------------------------------------------------- 1 | function solve_euler(timestep::Float64, n::Int64) 2 | euler_result = Vector{Float64}(undef, n) 3 | 4 | # Setting the initial condition 5 | euler_result[1] = 1; 6 | for i = 2:length(euler_result) 7 | euler_result[i] = euler_result[i-1] - 3.0*euler_result[i-1]*timestep 8 | end 9 | return euler_result 10 | end 11 | 12 | function check_result(euler_result::Vector{Float64}, threshold::Float64, 13 | timestep::Float64) 14 | is_approx = true 15 | 16 | for i = 1:length(euler_result) 17 | time = (i - 1)*timestep 18 | solution = exp(-3*time); 19 | if (abs(euler_result[i] - solution) > threshold) 20 | println(euler_result[i], solution) 21 | is_approx = false 22 | end 23 | end 24 | 25 | return is_approx 26 | end 27 | 28 | function main() 29 | timestep = 0.01 30 | n = 100 31 | threshold = 0.01 32 | 33 | euler_result = solve_euler(timestep,n) 34 | is_approx = check_result(euler_result, threshold, timestep) 35 | 36 | println(is_approx) 37 | end 38 | 39 | main() 40 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/matlab/euler.m: -------------------------------------------------------------------------------- 1 | clc;clear;close all 2 | 3 | %========================================================================== 4 | % Define Function 5 | f =@(x) -3*x; 6 | 7 | % Define Initial and Final time 8 | tInit=0; 9 | tLast=5; 10 | 11 | % Define number of points 12 | N=1e2; 13 | 14 | % Set Initial Conditions 15 | yInit=1; 16 | %========================================================================== 17 | 18 | dt=(tLast-tInit)/(N-1); % Calculate dt 19 | t=[tInit:dt:tLast]; % Preallocate time array 20 | y=zeros(1,length(t)); % Preallocate solution array 21 | y(1)=yInit; % Impose Initial Conditions 22 | 23 | % Loop over time 24 | for i=1:length(t)-1 25 | 26 | t(i+1) = t(i) + dt; % Calculate next time 27 | y(i+1) = y(i) + f( y(i) )*dt; % Update solution 28 | 29 | end 30 | 31 | % Plot numerical solution 32 | plot(t,y) 33 | 34 | % Create analytical solution 35 | g=@(x) exp(-3*x); 36 | z=g(t); 37 | 38 | % Plot analytical solution on the same graph 39 | hold on 40 | plot(t,z,'--') 41 | 42 | % Set axis, title and legend 43 | xlabel('t');ylabel('y(t)'); 44 | title('Analytical VS Numerical Solution') 45 | grid 46 | legend('Numerical','Analytical') 47 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/nim/forwardeuler.nim: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | proc solveEuler(timestep: float, n: int): seq[float] = 4 | var res = newSeq[float](n) 5 | 6 | res[0] = 1.0 7 | 8 | for i in 1 .. n - 1: 9 | res[i] = res[i - 1] - 3 * res[i - 1] * timestep 10 | 11 | return res 12 | 13 | proc check(res: seq[float], timestep, threshold: float): bool = 14 | var approx: bool = true; 15 | 16 | for i in 0 .. len(res) - 1: 17 | let solution: float = exp(-3.0 * float(i) * timestep) 18 | if abs(res[i]) - solution > threshold: 19 | echo res[i] 20 | echo solution 21 | approx = false 22 | 23 | return approx 24 | 25 | const 26 | timestep: float = 0.1 27 | n: int = 100 28 | threshold: float = 0.1 29 | eulerResult: seq[float] = solveEuler(timestep, n) 30 | approx: bool = check(eulerResult, threshold, timestep) 31 | 32 | echo approx 33 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/python/euler.py: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | 4 | def forward_euler(time_step, n): 5 | result = [0] * n 6 | result[0] = 1 7 | for i in range(1, n): 8 | result[i] = result[i - 1] - 3 * result[i - 1] * time_step 9 | return result 10 | 11 | 12 | def check(result, threshold, time_step): 13 | approx = True 14 | for i in range(len(result)): 15 | solution = math.exp(-3 * i * time_step) 16 | if abs(result[i] - solution) > threshold: 17 | print(result[i], solution) 18 | approx = False 19 | return approx 20 | 21 | 22 | def main(): 23 | time_step = 0.01 24 | n = 100 25 | threshold = 0.01 26 | 27 | result = forward_euler(time_step, n) 28 | approx = check(result, threshold, time_step) 29 | print("All values within threshold") if approx else print("Value(s) not in threshold") 30 | 31 | main() 32 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/rust/euler.rs: -------------------------------------------------------------------------------- 1 | fn main() { 2 | let mut result = [0.0; 100]; 3 | let threshold = 0.01; 4 | let timestep = 0.01; 5 | 6 | solve_euler(timestep, &mut result); 7 | println!("{}", check_result(&result, threshold, timestep)); 8 | } 9 | 10 | fn solve_euler(timestep: f64, result: &mut [f64]) { 11 | let n = result.len(); 12 | if n != 0 { 13 | result[0] = 1.0; 14 | for i in 1..n { 15 | result[i] = result[i - 1] - 3.0 * result[i - 1] * timestep; 16 | } 17 | } 18 | } 19 | 20 | fn check_result(result: &[f64], threshold: f64, timestep: f64) -> bool { 21 | let mut is_approx: bool = true; 22 | for (i, val) in result.iter().enumerate() { 23 | let solution = (-3.0 * i as f64 * timestep).exp(); 24 | if (val - solution).abs() > threshold { 25 | println!("{} {}", val, solution); 26 | is_approx = false; 27 | } 28 | } 29 | 30 | return is_approx; 31 | } 32 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/swift/euler.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | func solveEuler(timeStep: Double, n: Int) -> [Double] { 4 | var result : [Double] = [1] 5 | 6 | for i in 1...n { 7 | result.append(result[i - 1] - 3 * result[i - 1] * timeStep) 8 | } 9 | 10 | return result 11 | } 12 | 13 | func checkResult(result: [Double], threshold: Double, timeStep: Double) -> Bool { 14 | var isApprox = true 15 | 16 | for i in 0.. threshold { 19 | print(result[i], solution) 20 | isApprox = false 21 | } 22 | } 23 | 24 | return isApprox 25 | } 26 | 27 | func main() { 28 | let timeStep = 0.01 29 | let n = 100 30 | let threshold = 0.01 31 | 32 | let result = solveEuler(timeStep: timeStep, n: n) 33 | let isApprox = checkResult(result: result, threshold: threshold, timeStep: timeStep) 34 | 35 | if isApprox { 36 | print("All values within threshold") 37 | } else { 38 | print("Value(s) not in threshold") 39 | } 40 | } 41 | 42 | main() 43 | -------------------------------------------------------------------------------- /contents/forward_euler_method/code/v/euler.v: -------------------------------------------------------------------------------- 1 | import math 2 | 3 | fn forward_euler(timestep f64, n int) []f64 { 4 | mut res := [f64(0.0)].repeat(n) 5 | res[0] = f64(1) 6 | for x := 1; x < n; x++ { 7 | res[x] = res[x-1] - 3.0*res[x-1]*timestep 8 | } 9 | return res 10 | } 11 | 12 | fn check(result []f64, threshold, timestep f64) bool { 13 | mut approx := true 14 | for x := 0; x < result.len; x++ { 15 | solution := math.exp(-3.0 * f64(x) * timestep) 16 | if math.abs(result[x]-solution) > threshold { 17 | tmp := result[x] 18 | println("There is a mismatch: abs($tmp-$solution) > $threshold!") 19 | approx = false 20 | } 21 | } 22 | return approx 23 | } 24 | 25 | fn main() { 26 | timestep := .01 27 | threshold := .01 28 | n := 100 29 | 30 | result := forward_euler(timestep, n) 31 | 32 | if check(result, threshold, timestep) { 33 | println("All values within threshold") 34 | } else { 35 | println("Value(s) not within threshold") 36 | } 37 | } -------------------------------------------------------------------------------- /contents/forward_euler_method/res/error.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/forward_euler_method/res/error.png -------------------------------------------------------------------------------- /contents/forward_euler_method/res/instability.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/forward_euler_method/res/instability.png -------------------------------------------------------------------------------- /contents/gaussian_elimination/res/GE_vis.mp4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/gaussian_elimination/res/GE_vis.mp4 -------------------------------------------------------------------------------- /contents/graham_scan/code/c/SConscript: -------------------------------------------------------------------------------- 1 | Import('*') 2 | from pathlib import Path 3 | 4 | dirname = Path.cwd().parents[1].stem 5 | 6 | env.C(f'#/build/c/{dirname}', Glob('*.c'), LIBS='m') 7 | -------------------------------------------------------------------------------- /contents/graham_scan/code/haskell/grahamScan.hs: -------------------------------------------------------------------------------- 1 | import Data.List (sortOn, minimumBy) 2 | import Data.Function (on) 3 | 4 | type Point = (Double, Double) 5 | 6 | ccw :: Point -> Point -> Point -> Double 7 | ccw (xa, ya) (xb, yb) (xc, yc) = (xb - xa) * (yc - ya) - (yb - ya) * (xc - xa) 8 | 9 | grahamScan :: [Point] -> [Point] 10 | grahamScan [] = [] 11 | grahamScan pts = wrap sortedPts [p0] 12 | where p0@(x, y)= minimumBy (compare `on` snd) pts 13 | sortedPts = sortOn (\(px, py) -> atan2 (py-y) (px-x) ) $ filter (/=p0) pts 14 | wrap [] ps = ps 15 | wrap (s:ss) [p] = wrap ss [s, p] 16 | wrap (s:ss) (p1:p2:ps) 17 | | ccw s p1 p2 > 0 = wrap (s:ss) (p2:ps) 18 | | otherwise = wrap ss (s:p1:p2:ps) 19 | 20 | main = do 21 | -- We build the set of points of integer coordinates within a circle of radius 5 22 | let pts = [(x,y) | x<-[-5..5], y<-[-5..5], x^2+y^2<=5^2] 23 | -- And extract the convex hull 24 | print $ grahamScan pts 25 | -------------------------------------------------------------------------------- /contents/how_to_contribute/res/codeblock.txt: -------------------------------------------------------------------------------- 1 | {% method %} 2 | {% sample lang="jl" %} 3 | [import:1-17, lang:"julia"](code/julia/conv.jl) 4 | {% endmethod %} 5 | 6 | -------------------------------------------------------------------------------- /contents/huffman_encoding/code/csharp/Program.cs: -------------------------------------------------------------------------------- 1 | // submitted by Julian Schacher (jspp), thanks to gustorn for the help 2 | using System.Collections; 3 | using System.Collections.Generic; 4 | 5 | namespace HuffmanCoding 6 | { 7 | class Program 8 | { 9 | static void Main(string[] args) 10 | { 11 | var huffmanCoding = new HuffmanCoding(); 12 | 13 | var result = huffmanCoding.Encode("bibbity bobbity"); 14 | // The bitStrings are just strings and provide no compression. Look in HuffmanCoding.cs for explanation. 15 | // Print dictionary. 16 | foreach (var entry in result.Dictionary) 17 | System.Console.WriteLine($"{entry.Key} {entry.Value}"); 18 | // Print BitString. 19 | System.Console.WriteLine($"{result.BitString} count: {result.BitString.Length}"); 20 | 21 | var originalString = huffmanCoding.Decode(result); 22 | System.Console.WriteLine(originalString); 23 | } 24 | } 25 | } -------------------------------------------------------------------------------- /contents/huffman_encoding/code/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "huffman" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | itertools = "0.10.1" 10 | 11 | [[bin]] 12 | path = "./huffman.rs" 13 | name = "main" -------------------------------------------------------------------------------- /contents/huffman_encoding/res/huffman_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/huffman_encoding/res/huffman_tree.png -------------------------------------------------------------------------------- /contents/jarvis_march/code/haskell/jarvisMarch.hs: -------------------------------------------------------------------------------- 1 | import Data.List (sort, maximumBy) 2 | import Data.Function (on) 3 | 4 | type Point = (Double, Double) 5 | 6 | angle :: Point -> Point -> Point -> Double 7 | angle a@(xa, ya) b@(xb, yb) c@(xc, yc) 8 | | a==b || c==b = 0 9 | | theta<0 = theta+2*pi 10 | | otherwise = theta 11 | where thetaA = atan2 (ya-yb) (xa-xb) 12 | thetaC = atan2 (yc-yb) (xc-xb) 13 | theta = thetaC - thetaA 14 | 15 | jarvisMarch :: [Point] -> [Point] 16 | jarvisMarch [] = [] 17 | jarvisMarch pts = p0 : wrap (x, y-1) p0 18 | where p0@(x, y)= minimum pts 19 | wrap p1 p2 20 | | pm == p0 = [] 21 | | otherwise = pm : wrap p2 pm 22 | where pm = maximumBy (compare `on` angle p1 p2) pts 23 | 24 | main = do 25 | let pts = filter (\(x,y) -> x^2+y^2<=5^2) [(x,y)|x<-[-5..5], y<-[-5..5]] 26 | print $ jarvisMarch pts 27 | -------------------------------------------------------------------------------- /contents/jarvis_march/code/javascript/jarvis-march.js: -------------------------------------------------------------------------------- 1 | function jarvisMarch(points) { 2 | const hull = []; 3 | 4 | let pointOnHull = points.reduce((leftmost, current) => leftmost.x < current.x ? leftmost : current); 5 | do { 6 | hull.push(pointOnHull); 7 | pointOnHull = points.reduce(chooseNextPointOnHull(pointOnHull)); 8 | } while (pointOnHull !== hull[0]); 9 | 10 | return hull; 11 | } 12 | 13 | function chooseNextPointOnHull(currentPoint) { 14 | return function (nextPoint, candidate) { 15 | if (nextPoint === currentPoint || isLeftOf({ a: currentPoint, b: nextPoint }, candidate)) { 16 | return candidate; 17 | } 18 | return nextPoint; 19 | } 20 | } 21 | 22 | function isLeftOf({ a, b }, p) { 23 | return (b.x - a.x) * (p.y - a.y) > (p.x - a.x) * (b.y - a.y); 24 | } 25 | 26 | const points = [ 27 | { x: 1, y: 3 }, 28 | { x: 2, y: 4 }, 29 | { x: 4, y: 0 }, 30 | { x: 1, y: 0 }, 31 | { x: 0, y: 2 }, 32 | { x: 2, y: 2 }, 33 | { x: 3, y: 4 }, 34 | { x: 3, y: 1 }, 35 | ]; 36 | 37 | const convexHull = jarvisMarch(points); 38 | convexHull.forEach(p => console.log(`(${p.x}, ${p.y})`)); 39 | 40 | -------------------------------------------------------------------------------- /contents/jarvis_march/code/python/jarvis_march.py: -------------------------------------------------------------------------------- 1 | # Is the turn counter clockwise? 2 | def ccw(p1, p2, p3): 3 | return (p3[1] - p1[1]) * (p2[0] - p1[0]) \ 4 | >= (p2[1] - p1[1]) * (p3[0] - p1[0]) 5 | 6 | 7 | def jarvis_march(gift): 8 | n = len(gift) # Number of points in list 9 | point_on_hull = min(gift) # leftmost point in gift 10 | hull = [point_on_hull] # leftmost point guaranteed to be in hull 11 | 12 | while True: 13 | # Candidate for next point in hull 14 | endpoint = gift[0] 15 | for j in range(1, n): 16 | if endpoint == point_on_hull \ 17 | or not ccw(gift[j], hull[-1], endpoint): 18 | endpoint = gift[j] 19 | 20 | point_on_hull = endpoint 21 | 22 | # Check if we have completely wrapped gift 23 | if hull[0] == endpoint: 24 | break 25 | else: 26 | hull.append(point_on_hull) 27 | 28 | return hull 29 | 30 | 31 | def main(): 32 | test_gift = [ 33 | (-5, 2), (5, 7), (-6, -12), (-14, -14), (9, 9), 34 | (-1, -1), (-10, 11), (-6, 15), (-6, -8), (15, -9), 35 | (7, -7), (-2, -9), (6, -5), (0, 14), (2, 8) 36 | ] 37 | hull = jarvis_march(test_gift) 38 | 39 | print("The points in the hull are:") 40 | for point in hull: 41 | print(point) 42 | 43 | 44 | if __name__ == "__main__": 45 | main() 46 | -------------------------------------------------------------------------------- /contents/makefiles/makefiles.md: -------------------------------------------------------------------------------- 1 | ## Makefiles 2 | 3 | COMING SOON! 4 | 5 | ## License 6 | 7 | ##### Code Examples 8 | 9 | The code examples are licensed under the MIT license (found in [LICENSE.md](https://github.com/algorithm-archivists/algorithm-archive/blob/main/LICENSE.md)). 10 | 11 | ##### Text 12 | 13 | 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). 14 | 15 | [

](https://creativecommons.org/licenses/by-sa/4.0/) 16 | 17 | ##### Pull Requests 18 | 19 | After initial licensing ([#560](https://github.com/algorithm-archivists/algorithm-archive/pull/560)), the following pull requests have modified the text or graphics of this chapter: 20 | - none 21 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/bash/monte_carlo.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | inCircle() { 3 | local ret 4 | local mag 5 | ((ret = 0)) 6 | if (($1 ** 2 + $2 ** 2 < 1073676289)); then # 1073676289 = 32767 ** 2 7 | ((ret = 1)) 8 | fi 9 | printf "%d" $ret 10 | } 11 | 12 | monteCarlo() { 13 | local count 14 | local i 15 | ((count = 0)) 16 | for ((i = 0; i < $1; i++)); do 17 | if (($(inCircle RANDOM RANDOM) == 1)); then 18 | ((count++)) 19 | fi 20 | done 21 | echo "scale = 8; 4 * $count / $1" | bc 22 | } 23 | 24 | est=$(monteCarlo 10000) 25 | echo "The estimate of pi is $est" 26 | echo "Percentage error: $(echo "scale = 8; 100 * sqrt( ( 1 - $est / (4*a(1)) ) ^ 2 )" | bc -l)" 27 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/c/monte_carlo.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | 7 | bool in_circle(double x, double y) { 8 | return x * x + y * y < 1; 9 | } 10 | 11 | double monte_carlo(unsigned int samples) { 12 | unsigned int count = 0; 13 | 14 | for (unsigned int i = 0; i < samples; ++i) { 15 | double x = (double)rand() / RAND_MAX; 16 | double y = (double)rand() / RAND_MAX; 17 | 18 | if (in_circle(x, y)) { 19 | count += 1; 20 | } 21 | } 22 | 23 | return 4.0 * count / samples; 24 | } 25 | 26 | int main() { 27 | srand(time(NULL)); 28 | 29 | double estimate = monte_carlo(1000000); 30 | 31 | printf("The estimate of pi is %g\n", estimate); 32 | printf("Percentage error: %0.2f%%\n", 100 * fabs(M_PI - estimate) / M_PI); 33 | 34 | return 0; 35 | } 36 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/clisp/monte-carlo.lisp: -------------------------------------------------------------------------------- 1 | ;;;; Monte carlo integration to approximate pi 2 | 3 | (defun in-circle-p (x y) 4 | "Checks if a point is in a unit circle" 5 | (< (+ (* x x) (* y y)) 1)) 6 | 7 | (defun monte-carlo (samples) 8 | "Returns an approximation of pi" 9 | (loop repeat samples 10 | with count = 0 11 | do 12 | (when (in-circle-p (random 1.0) (random 1.0)) 13 | (incf count)) 14 | finally (return (* (/ count samples) 4.0)))) 15 | 16 | (defvar pi-estimate (monte-carlo 5000000)) 17 | (format t "Estimate: ~D ~%" pi-estimate) 18 | (format t "Error: ~D%" (* (/ (abs (- pi-estimate pi)) pi) 100)) 19 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/clojure/monte_carlo.clj: -------------------------------------------------------------------------------- 1 | (ns monte-carlo.core) 2 | 3 | (defn in-circle? [pv r] 4 | "take a vector representing point and radius return true if the 5 | point is inside the circle" 6 | (< (->> 7 | pv 8 | (map #(* % %)) 9 | (reduce +)) 10 | (* r r))) 11 | 12 | (defn rand-point [r] 13 | "return a random point from (0,0) inclusive to (r,r) exclusive" 14 | (repeatedly 2 #(rand r))) 15 | 16 | (defn monte-carlo [n r] 17 | "take the number of random points and radius return an estimate to 18 | pi" 19 | (*' 4 (/ n) 20 | (loop [i n count 0] 21 | (if (zero? i) 22 | count 23 | (recur (dec i) 24 | (if (in-circle? (rand-point r) r) 25 | (inc count) 26 | count)))))) 27 | 28 | (defn -main [] 29 | (let [constant-pi Math/PI 30 | computed-pi (monte-carlo 10000000 2) ;; this may take some time on lower end machines 31 | difference (Math/abs (- constant-pi computed-pi)) 32 | error (* 100 (/ difference constant-pi))] 33 | (println "world's PI: " constant-pi 34 | ",our PI: " (double computed-pi) 35 | ",error: " error))) 36 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/coconut/monte_carlo.coco: -------------------------------------------------------------------------------- 1 | import math 2 | import random 3 | 4 | data point(x, y): 5 | def __abs__(self) = (self.x, self.y) |> map$(pow$(?, 2)) |> sum |> math.sqrt 6 | 7 | def in_circle(p is point, radius = 1): 8 | """Return True if the point is in the circle and False otherwise.""" 9 | return abs(p) < radius 10 | 11 | def monte_carlo(n_samples, radius = 1) = (range(n_samples) 12 | |> map$(-> point(random.uniform(0, radius), random.uniform(0, radius))) 13 | |> filter$(in_circle$(?, radius)) 14 | |> tuple 15 | |> len) * 4 / n_samples 16 | 17 | if __name__ == '__main__': 18 | 19 | samples = 100_000 20 | 21 | print(f"Using {samples:_} samples.") 22 | 23 | pi_estimate = monte_carlo(samples) 24 | percent_error = 100*abs(math.pi - pi_estimate)/math.pi 25 | 26 | print("The estimate of pi is: {:.3f}".format(pi_estimate)) 27 | print("The percent error is: {:.3f}".format(percent_error)) 28 | 29 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/csharp/Circle.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MonteCarloIntegration 4 | { 5 | public struct Point 6 | { 7 | public double X { get; set; } 8 | public double Y { get; set; } 9 | 10 | public Point(double x, double y) 11 | { 12 | this.X = x; 13 | this.Y = y; 14 | } 15 | } 16 | 17 | public class Circle 18 | { 19 | public double Radius { get; private set; } 20 | 21 | public Circle(double radius) => this.Radius = Math.Abs(radius); 22 | 23 | public bool IsInMe(Point point) => Math.Pow(point.X, 2) + Math.Pow(point.Y, 2) < Math.Pow(Radius, 2); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/csharp/MonteCarlo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MonteCarloIntegration 4 | { 5 | public class MonteCarlo 6 | { 7 | public double Run(int samples) 8 | { 9 | var circle = new Circle(1.0); 10 | var count = 0; 11 | var random = new Random(); 12 | 13 | for (int i = 0; i < samples; i++) 14 | { 15 | var point = new Point(random.NextDouble(), random.NextDouble()); 16 | if (circle.IsInMe(point)) 17 | count++; 18 | } 19 | 20 | return 4.0 * count / samples; 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/csharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace MonteCarloIntegration 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | var monteCarlo = new MonteCarlo(); 10 | System.Console.WriteLine("Running with 10,000,000 samples."); 11 | var piEstimate = monteCarlo.Run(10000000); 12 | System.Console.WriteLine($"The estimate of pi is: {piEstimate}"); 13 | System.Console.WriteLine($"The percent error is: {Math.Abs(piEstimate - Math.PI) / Math.PI * 100}%"); 14 | } 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/d/monte_carlo.d: -------------------------------------------------------------------------------- 1 | ///Returns true if a point (x, y) is in the circle with radius r 2 | bool inCircle(real x, real y) 3 | { 4 | return x ^^ 2 + y ^^ 2 < 1.0; 5 | } 6 | 7 | ///Calculate pi using monte carlo 8 | real monteCarloPI(ulong n) 9 | { 10 | import std.algorithm : count; 11 | import std.random : uniform01; 12 | import std.range : generate, take; 13 | import std.typecons : tuple; 14 | 15 | auto piCount = generate(() => tuple!("x", "y")(uniform01, uniform01)) 16 | .take(n) 17 | .count!(a => inCircle(a.x, a.y)); 18 | return piCount * 4.0 / n; 19 | } 20 | 21 | void main() 22 | { 23 | import std.math : abs, PI; 24 | import std.stdio : writeln; 25 | 26 | auto p = monteCarloPI(100_000); 27 | writeln("Estimated pi: ", p); 28 | writeln("Percent error: ", abs(p - PI) * 100 / PI); 29 | } 30 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/emojicode/monte_carlo.emojic: -------------------------------------------------------------------------------- 1 | 🐇 ☝️ 🍇 2 | 🖍🆕 x 💯 3 | 🖍🆕 y 💯 4 | 5 | 🆕 🍼 x 💯 🍼 y 💯 🍇 🍉 6 | 7 | ❗️ 📪 ➡️ 💯 🍇 8 | ↩️ x 9 | 🍉 10 | 11 | ❗️ 📫 ➡️ 💯 🍇 12 | ↩️ y 13 | 🍉 14 | 🍉 15 | 16 | 🐇 🌕 🍇 17 | 🖍🆕 radius 💯 18 | 19 | 🆕 given_radius 💯 🍇 20 | 🏧 given_radius❗️ ➡️ 🖍radius 21 | 🍉 22 | 23 | ❗️ 📥 point ☝️ ➡️ 👌 🍇 24 | 📪 point❗️ ➡️ point_x 25 | 📫 point❗️ ➡️ point_y 26 | ↩️ 🤜point_x ✖️ point_x ➕ point_y ✖️ point_y🤛 ◀️ 🤜radius ✖️ radius🤛 27 | 🍉 28 | 🍉 29 | 30 | 🐇 🤡 🍇 31 | 🐇 ❗️ 🏃‍♀️ samples 🔢 ➡️ 💯 🍇 32 | 🆕🌕🆕 1.0 ❗️ ➡️ circle 33 | 0 ➡️ 🖍🆕 count 34 | 35 | 🆕🎰🆕 ❗️ ➡️ random 36 | 37 | 🔂 i 🆕⏩⏩ 0 samples❗️ 🍇 38 | 🆕☝️🆕 💯 random❗️ 💯 random❗️❗️ ➡️ point 39 | ↪️ 📥 circle point❗️ 🍇 40 | count ⬅️ ➕ 1 41 | 🍉 42 | 🍉 43 | 44 | ↩️ 4.0 ✖️ 💯 count❗️ ➗ 💯samples❗️ 45 | 🍉 46 | 🍉 47 | 48 | 🏁 🍇 49 | 😀 🔤Running with 10,000,000 samples.🔤❗️ 50 | 🏃‍♀️🐇🤡 10000000❗️ ➡️ pi_estimate 51 | 😀 🍪🔤The estimate of pi is: 🔤 🔡 pi_estimate 10❗🍪❗️ 52 | 🏧 🤜pi_estimate ➖ 🥧🕊💯 ❗️🤛❗️ ➗ 🥧🕊💯 ❗️ ✖️ 100 ➡️ percent_error 53 | 😀 🍪🔤The percent error is: 🔤 🔡 percent_error 10❗ 🔤%🔤🍪❗️ 54 | 🍉 55 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/factor/monte_carlo.factor: -------------------------------------------------------------------------------- 1 | USING: locals random math.ranges math.functions ; 2 | 3 | :: monte-carlo ( n in-shape?: ( x y -- ? ) -- % ) 4 | n [ drop random-unit random-unit in-shape? call ] count n / 5 | ; inline 6 | 7 | ! Use the monte-carlo approximation to calculate pi 8 | : monte-carlo-pi ( n -- pi-approx ) 9 | [ ! in-circle check 10 | [ 2 ^ ] bi@ + ! get the distance from the center 11 | 1 < ! see if it's less than the radius 12 | ] 13 | monte-carlo 4 * >float 14 | ; 15 | 16 | USING: math.constants ; 17 | 10000000 monte-carlo-pi ! Approximate pi 18 | dup . ! Print the approximation 19 | pi - pi / 100 * >float abs . ! And the error margin 20 | 21 | 22 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/go/monteCarlo.go: -------------------------------------------------------------------------------- 1 | // Submitted by Chinmaya Mahesh (chin123) 2 | 3 | package main 4 | 5 | import ( 6 | "fmt" 7 | "math" 8 | "math/rand" 9 | "time" 10 | ) 11 | 12 | func inCircle(x, y float64) bool { 13 | return x*x+y*y < 1.0 // the radius of an unit circle is 1.0 14 | } 15 | 16 | func monteCarlo(samples int) { 17 | count := 0 18 | s := rand.NewSource(time.Now().UnixNano()) 19 | r := rand.New(s) 20 | 21 | for i := 0; i < samples; i++ { 22 | x, y := r.Float64(), r.Float64() 23 | 24 | if inCircle(x, y) { 25 | count += 1 26 | } 27 | } 28 | 29 | estimate := 4.0 * float64(count) / float64(samples) 30 | 31 | fmt.Println("The estimate of pi is", estimate) 32 | fmt.Printf("Which has an error of %f%%\n", 100*math.Abs(math.Pi-estimate)/math.Pi) 33 | } 34 | 35 | func main() { 36 | monteCarlo(10000000) 37 | } 38 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/haskell/monteCarlo.hs: -------------------------------------------------------------------------------- 1 | import System.Random 2 | 3 | monteCarloPi :: RandomGen g => g -> Int -> Float 4 | monteCarloPi g n = count $ filter inCircle $ makePairs 5 | where makePairs = take n $ toPair (randomRs (0, 1) g :: [Float]) 6 | toPair (x:y:rest) = (x, y) : toPair rest 7 | inCircle (x, y) = x^2 + y^2 < 1 8 | count l = 4 * fromIntegral (length l) / fromIntegral n 9 | 10 | main = do 11 | g <- newStdGen 12 | let p = monteCarloPi g 100000 13 | putStrLn $ "Estimated pi: " ++ show p 14 | putStrLn $ "Percent error: " ++ show (100 * abs (pi - p) / pi) 15 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/java/MonteCarlo.java: -------------------------------------------------------------------------------- 1 | import java.util.Random; 2 | 3 | public class MonteCarlo { 4 | 5 | public static void main(String[] args) { 6 | double piEstimation = monteCarlo(1000); 7 | System.out.println("Estimated pi value: " + piEstimation); 8 | System.out.printf("Percent error: " + 100 * Math.abs(piEstimation - Math.PI) / Math.PI); 9 | } 10 | 11 | // function to check whether point (x,y) is in unit circle 12 | private static boolean inCircle(double x, double y) { 13 | return x * x + y * y < 1; 14 | } 15 | 16 | // function to calculate estimation of pi 17 | public static double monteCarlo(int samples) { 18 | int piCount = 0; 19 | 20 | Random random = new Random(); 21 | 22 | for (int i = 0; i < samples; i++) { 23 | double x = random.nextDouble(); 24 | double y = random.nextDouble(); 25 | if (inCircle(x, y)) { 26 | piCount++; 27 | } 28 | } 29 | 30 | return 4.0 * piCount / samples; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/javascript/monte_carlo.js: -------------------------------------------------------------------------------- 1 | // submitted by xam4lor 2 | function inCircle(xPos, yPos) { 3 | // Setting radius to 1 for unit circle 4 | let radius = 1; 5 | return xPos * xPos + yPos * yPos < radius * radius; 6 | } 7 | 8 | function monteCarlo(n) { 9 | let piCount = 0; 10 | 11 | for (let i = 0; i < n; i++) { 12 | const pointX = Math.random(); 13 | const pointY = Math.random(); 14 | 15 | if (inCircle(pointX, pointY)) { 16 | piCount++; 17 | } 18 | } 19 | 20 | // This is using a quarter of the unit sphere in a 1x1 box. 21 | // The formula is pi = (boxLength^2 / radius^2) * (piCount / n), but we 22 | // are only using the upper quadrant and the unit circle, so we can use 23 | // 4*piCount/n instead 24 | // piEstimate = 4*piCount/n 25 | const piEstimate = 4 * piCount / n; 26 | console.log('Percent error is: %s%', 100 * Math.abs(piEstimate - Math.PI) / Math.PI); 27 | } 28 | 29 | monteCarlo(100000000); 30 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/julia/monte_carlo.jl: -------------------------------------------------------------------------------- 1 | # function to determine whether an x, y point is in the unit circle 2 | function in_circle(x_pos::Float64, y_pos::Float64) 3 | 4 | # Setting radius to 1 for unit circle 5 | radius = 1 6 | return x_pos^2 + y_pos^2 < radius^2 7 | end 8 | 9 | # function to integrate a unit circle to find pi via monte_carlo 10 | function monte_carlo(n::Int64) 11 | 12 | pi_count = 0 13 | for i = 1:n 14 | point_x = rand() 15 | point_y = rand() 16 | 17 | if (in_circle(point_x, point_y)) 18 | pi_count += 1 19 | end 20 | end 21 | 22 | # This is using a quarter of the unit sphere in a 1x1 box. 23 | # The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we 24 | # are only using the upper quadrant and the unit circle, so we can use 25 | # 4*pi_count/n instead 26 | return 4*pi_count/n 27 | end 28 | 29 | pi_estimate = monte_carlo(10000000) 30 | println("The pi estimate is: ", pi_estimate) 31 | println("Percent error is: ", 100 * abs(pi_estimate - pi) / pi, " %") 32 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/kotlin/MonteCarlo.kt: -------------------------------------------------------------------------------- 1 | import java.util.Random 2 | 3 | private fun inCircle(x: Double, y: Double, radius: Double = 1.0) = (x * x + y * y) < radius * radius 4 | 5 | fun monteCarlo(samples: Int): Double { 6 | var piCount = 0 7 | val random = Random() 8 | 9 | for (i in 0 until samples) { 10 | val x = random.nextDouble() 11 | val y = random.nextDouble() 12 | if (inCircle(x, y)) 13 | piCount++ 14 | } 15 | return 4.0 * piCount / samples 16 | } 17 | 18 | fun main(args: Array) { 19 | val piEstimate = monteCarlo(100000) 20 | println("Estimated pi value: $piEstimate") 21 | val percentError = 100 * Math.abs(piEstimate - Math.PI) / Math.PI 22 | println("Percent error: $percentError") 23 | } 24 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/lua/monte_carlo.lua: -------------------------------------------------------------------------------- 1 | -- function to determine whether an x, y point is in the unit circle 2 | local function in_circle(x, y) 3 | return x*x + y*y < 1 4 | end 5 | 6 | -- function to integrate a unit circle to find pi via monte_carlo 7 | function monte_carlo(nsamples) 8 | local count = 0 9 | 10 | for i = 1,nsamples do 11 | if in_circle(math.random(), math.random()) then 12 | count = count + 1 13 | end 14 | end 15 | 16 | -- This is using a quarter of the unit sphere in a 1x1 box. 17 | -- The formula is pi = (box_length^2 / radius^2) * (pi_count / n), but we 18 | -- are only using the upper quadrant and the unit circle, so we can use 19 | -- 4*pi_count/n instead 20 | return 4 * count/nsamples 21 | end 22 | 23 | local pi = monte_carlo(10000000) 24 | print("Estimate: " .. pi) 25 | print(("Error: %.2f%%"):format(100*math.abs(pi-math.pi)/math.pi)) 26 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/matlab/monte.m: -------------------------------------------------------------------------------- 1 | pi_estimate = monte_carlo(10000000); 2 | 3 | fprintf("The pi estimate is: %f\n", pi_estimate); 4 | fprintf("Percent error is: %f%%\n", 100 * abs(pi_estimate - pi) / pi); 5 | 6 | function pi_estimate=monte_carlo(n) 7 | 8 | % a 2 by n array, rows are xs and ys 9 | xy_array = rand(2, n); 10 | 11 | % square every element in the array 12 | squares_array = xy_array.^2; 13 | 14 | % sum the xs and ys and check if it's in the quarter circle 15 | incircle_array = sum(squares_array)<1; 16 | 17 | % determine the average number of points in the circle 18 | pi_estimate = 4*sum(incircle_array)/n; 19 | 20 | end 21 | 22 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/nim/monte_carlo.nim: -------------------------------------------------------------------------------- 1 | import random 2 | import math 3 | 4 | randomize() 5 | 6 | proc in_circle(x, y, radius: float): bool = 7 | return x * x + y * y < radius * radius 8 | 9 | proc monte_carlo(samples: int): float = 10 | const radius: float = 1 11 | var count: int = 0 12 | 13 | for i in 0 .. < samples: 14 | let 15 | x: float = random(radius) 16 | y: float = random(radius) 17 | 18 | if in_circle(x, y, radius): 19 | count += 1 20 | 21 | let pi_estimate: float = 4 * count / samples 22 | return pi_estimate 23 | 24 | let estimate: float = monte_carlo(1000000) 25 | 26 | echo "the estimate of pi is ", estimate 27 | echo "percent error: ", 100 * (abs(estimate - PI)/PI) -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/php/monte_carlo.php: -------------------------------------------------------------------------------- 1 | string pi-estimate))) 24 | (displayln (string-append "Estimate (float): " (number->string (real->single-flonum pi-estimate)))) 25 | (displayln (string-append "Error:" (number->string (* (/ (abs (- pi-estimate pi)) pi) 100)))) 26 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/ruby/monte_carlo.rb: -------------------------------------------------------------------------------- 1 | def in_circle(x, y, radius=1) 2 | # Check if coords are in circle via Pythagorean Thm 3 | return (x*x + y*y) < radius*radius 4 | end 5 | 6 | def monte_carlo(n_samples, radius=1) 7 | # estimate pi via monte carlo sampling 8 | in_circle_count = 0.0 9 | 10 | for _ in 0...n_samples 11 | # randomly choose coords within square 12 | x = rand()*radius 13 | y = rand()*radius 14 | if in_circle(x, y, radius) 15 | in_circle_count += 1 16 | end 17 | end 18 | 19 | # circle area is pi*r^2 and rect area is 4r^2 20 | # ratio between the two is then pi/4 so multiply by 4 to get pi 21 | return 4 * (in_circle_count / n_samples) 22 | 23 | end 24 | 25 | 26 | # Main 27 | pi_estimate = monte_carlo(100000) 28 | percent_error = 100 * (pi_estimate - Math::PI).abs / Math::PI 29 | 30 | puts "The estimate of pi is: #{pi_estimate.round(3)}" 31 | puts "The percent error is: #{percent_error.round(3)}" 32 | 33 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/rust/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "montecarlo" 3 | version = "0.1.0" 4 | edition = "2018" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | rand = "0.8.4" 10 | 11 | [[bin]] 12 | path = "./monte_carlo.rs" 13 | name = "main" -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/rust/monte_carlo.rs: -------------------------------------------------------------------------------- 1 | // Submitted by jess 3jane 2 | 3 | extern crate rand; 4 | 5 | use std::f64::consts::PI; 6 | 7 | fn in_circle(x: f64, y: f64, radius: f64) -> bool { 8 | x * x + y * y < radius * radius 9 | } 10 | 11 | fn monte_carlo(n: i64) -> f64 { 12 | let mut count = 0; 13 | 14 | for _ in 0..n { 15 | let x = rand::random(); 16 | let y = rand::random(); 17 | if in_circle(x, y, 1.0) { 18 | count += 1; 19 | } 20 | } 21 | 22 | // return our pi estimate 23 | (4 * count) as f64 / n as f64 24 | } 25 | 26 | fn main() { 27 | let pi_estimate = monte_carlo(10000000); 28 | 29 | println!( 30 | "Percent error is {:.3}%", 31 | (100.0 * (pi_estimate - PI).abs() / PI) 32 | ); 33 | } 34 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/scala/monte_carlo.scala: -------------------------------------------------------------------------------- 1 | object MonteCarlo { 2 | 3 | def inCircle(x: Double, y: Double) = x * x + y * y < 1 4 | 5 | def monteCarloPi(samples: Int) = { 6 | def randCoord = math.random() * 2 - 1 7 | 8 | var pointCount = 0 9 | 10 | for (_ <- 0 to samples) 11 | if (inCircle(randCoord, randCoord)) 12 | pointCount += 1 13 | 14 | 4.0 * pointCount / samples 15 | } 16 | 17 | def main(args: Array[String]): Unit = { 18 | val approxPi = monteCarloPi(1000) 19 | println("Estimated pi value: " + approxPi) 20 | println("Percent error: " + 100 * Math.abs(approxPi - Math.PI) / Math.PI) 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/scratch/monte_carlo.txt: -------------------------------------------------------------------------------- 1 | <(((x) * (x)) + ((y) * (y))) < ((radius) * (radius)) > 2 | 3 | 4 | define Monte Carlo with point number (num) 5 | set [Count v] to (0) 6 | repeat (num) 7 | set [x v] to (pick random (0.0) to (1.0)) 8 | set [y v] to (pick random (0.0) to (1.0)) 9 | if <(((x) * (x)) + ((y) * (y))) < ((radius) * (radius)) > then // the radius is 1 10 | change [Count] by (1) 11 | end 12 | end 13 | set [EstPI v] to ((4) * ((Count) / (num))) 14 | 15 | when @greenflag clicked 16 | set [PI v] to (3.1415926535897932384626433832795028841971493993) 17 | ask [Number of point?] and wait 18 | Monte Carlo with point number (answer) 19 | say [Pi estimate done.] for (2) seconds 20 | say (join [Estimate pi: ] (EstPI)) for (2) seconds 21 | say (join [Real Pi: ] (PI)) for (2) seconds 22 | say (join [Percent Error: ] (join ((([abs v] of ((EstPI) - (PI))) / (PI)) * (100)) [%])) for (2) seconds -------------------------------------------------------------------------------- /contents/monte_carlo_integration/code/swift/monte_carlo.swift: -------------------------------------------------------------------------------- 1 | func inCircle(x: Double, y: Double, radius: Double) -> Bool { 2 | return (x*x) + (y*y) < radius*radius 3 | } 4 | 5 | func monteCarlo(n: Int) -> Double { 6 | let radius: Double = 1 7 | var piCount = 0 8 | var randX: Double 9 | var randY: Double 10 | 11 | for _ in 0...n { 12 | randX = Double.random(in: 0.. Shuffle(this IList list, Random rng) 9 | { 10 | for (var i = 0; i < list.Count; i++) 11 | { 12 | var j = rng.Next(i, list.Count); 13 | var tmp = list[i]; 14 | list[i] = list[j]; 15 | list[j] = tmp; 16 | } 17 | return list; 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /contents/stable_marriage_problem/code/haskell/stableMarriage.hs: -------------------------------------------------------------------------------- 1 | import Data.Map as M (Map, (!)) 2 | import qualified Data.Map as M 3 | import Data.List (elemIndex) 4 | import Control.Monad.State 5 | 6 | stableMatching :: (Ord a, Ord b) => [(a, [b])] -> [(b, [a])] -> [(a, b)] 7 | stableMatching men women = evalState (propose (M.fromList women) men) M.empty 8 | 9 | propose :: (Ord a, Ord b) => Map b [a] -> 10 | [(a, [b])] -> 11 | State (Map b (a, [b])) [(a, b)] 12 | propose _ [] = get >>= return . map (\(w, (m,_)) -> (m, w)) . M.assocs 13 | propose women ((man, pref):bachelors) = do 14 | let theOne = head pref 15 | couples <- get 16 | case M.lookup theOne couples of 17 | Nothing -> do 18 | modify $ M.insert theOne (man, (tail pref)) 19 | propose women bachelors 20 | Just (boyfriend, planB) -> do 21 | let rank x = elemIndex x (women!theOne) 22 | if rank boyfriend < rank man 23 | then propose women $ (man, tail pref): bachelors 24 | else do 25 | modify $ M.insert theOne (man, (tail pref)) . M.delete theOne 26 | propose women $ (boyfriend, planB): bachelors 27 | 28 | main = do 29 | let aPref = [('A',"YXZ"), ('B',"ZYX"),('C', "XZY")] 30 | bPref = [('X',"BAC"), ('Y',"CBA"),('Z', "ACB")] 31 | print $ stableMatching aPref bPref 32 | -------------------------------------------------------------------------------- /contents/stacks_and_queues/code/typescript/queue.ts: -------------------------------------------------------------------------------- 1 | interface IQueue { 2 | /** 3 | * `dequeue` removes first element from the queue and returns the same 4 | */ 5 | dequeue(): T; 6 | /** 7 | * `enqueue` adds element to last of the queue and returns the size 8 | */ 9 | enqueue(data: T): number; 10 | /** 11 | * `size` return size or length of the queue 12 | */ 13 | size(): number; 14 | /** 15 | * `front` returns first element of the queue 16 | */ 17 | front(): T; 18 | } 19 | 20 | class Queue implements IQueue { 21 | private readonly list: Array = []; 22 | 23 | public enqueue(data: T) { 24 | return this.list.push(data); 25 | } 26 | 27 | public dequeue() { 28 | return this.list.shift(); 29 | } 30 | 31 | public size() { 32 | return this.list.length; 33 | } 34 | 35 | public front() { 36 | return this.list[0]; 37 | } 38 | } 39 | 40 | function exampleQueue() { 41 | const numberQueue = new Queue(); 42 | 43 | numberQueue.enqueue(4); 44 | numberQueue.enqueue(5); 45 | numberQueue.enqueue(9); 46 | 47 | console.log(numberQueue.dequeue()); 48 | console.log(numberQueue.size()); 49 | console.log(numberQueue.front()); 50 | } 51 | 52 | exampleQueue(); 53 | -------------------------------------------------------------------------------- /contents/stacks_and_queues/code/typescript/stack.ts: -------------------------------------------------------------------------------- 1 | interface IStack { 2 | /** 3 | * `pop` removes last element from the stack and returns the same 4 | */ 5 | pop(): T; 6 | /** 7 | * `push` adds element to last of the stack and returns the size 8 | */ 9 | push(data: T): number; 10 | /** 11 | * `size` return size or length of the stack 12 | */ 13 | size(): number; 14 | /** 15 | * `top` returns last element of the stack 16 | */ 17 | top(): T; 18 | } 19 | 20 | class Stack implements IStack { 21 | private readonly list: Array = []; 22 | 23 | public push(data: T) { 24 | return this.list.push(data); 25 | } 26 | 27 | public pop() { 28 | return this.list.pop(); 29 | } 30 | 31 | public size() { 32 | return this.list.length; 33 | } 34 | 35 | public top() { 36 | return this.list[this.list.length - 1]; 37 | } 38 | } 39 | 40 | function exampleStack() { 41 | const numberStack = new Stack(); 42 | 43 | numberStack.push(4); 44 | numberStack.push(5); 45 | numberStack.push(9); 46 | 47 | console.log(numberStack.pop()); 48 | console.log(numberStack.size()); 49 | console.log(numberStack.top()); 50 | } 51 | 52 | exampleStack(); 53 | -------------------------------------------------------------------------------- /contents/taylor_series_expansion/res/function_sum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/taylor_series_expansion/res/function_sum.png -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/c/thomas.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | void thomas(double * const a, double * const b, double * const c, 5 | double * const x, const size_t size) { 6 | 7 | double y[size]; 8 | memset(y, 0, size * sizeof(double)); 9 | 10 | y[0] = c[0] / b[0]; 11 | x[0] = x[0] / b[0]; 12 | 13 | for (size_t i = 1; i < size; ++i) { 14 | double scale = 1.0 / (b[i] - a[i] * y[i - 1]); 15 | y[i] = c[i] * scale; 16 | x[i] = (x[i] - a[i] * x[i - 1]) * scale; 17 | } 18 | 19 | for (int i = size - 2; i >= 0; --i) { 20 | x[i] -= y[i] * x[i + 1]; 21 | } 22 | } 23 | 24 | int main() { 25 | double a[] = {0.0, 2.0, 3.0}; 26 | double b[] = {1.0, 3.0, 6.0}; 27 | double c[] = {4.0, 5.0, 0.0}; 28 | double x[] = {7.0, 5.0, 3.0}; 29 | 30 | printf("The system,\n"); 31 | printf("[1.0 4.0 0.0][x] = [7.0]\n"); 32 | printf("[2.0 3.0 5.0][y] = [5.0]\n"); 33 | printf("[0.0 3.0 6.0][z] = [3.0]\n"); 34 | printf("has the solution:\n"); 35 | 36 | thomas(a, b, c, x, 3); 37 | 38 | for (size_t i = 0; i < 3; ++i) { 39 | printf("[%f]\n", x[i]); 40 | } 41 | 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/crystal/thomas.cr: -------------------------------------------------------------------------------- 1 | def thomas(a, b, c, d) 2 | c_prime = c.dup 3 | x = d.dup 4 | 5 | # Setting initial elements 6 | c_prime[0] /= b[0] 7 | x[0] /= b[0] 8 | 9 | 1.upto(a.size - 1) do |i| 10 | # Scale factor is for c_prime and x 11 | scale = 1.0 / (b[i] - c_prime[i - 1]*a[i]) 12 | c_prime[i] *= scale 13 | x[i] = (x[i] - a[i] * x[i - 1]) * scale 14 | end 15 | 16 | # Back-substitution 17 | (a.size - 2).downto(0) do |i| 18 | x[i] -= (c_prime[i] * x[i + 1]) 19 | end 20 | 21 | x 22 | end 23 | 24 | def main 25 | a = [0.0, 2.0, 3.0] 26 | b = [1.0, 3.0, 6.0] 27 | c = [4.0, 5.0, 0.0] 28 | d = [7.0, 5.0, 3.0] 29 | 30 | puts "The system" 31 | puts [b[0], c[0], "", "|", d[0]].join("\t") 32 | puts [a[1], b[1], c[1], "|", d[1]].join("\t") 33 | puts ["", a[2], b[2], "|", d[2]].join("\t") 34 | puts "Has the solution:" 35 | 36 | soln = thomas(a, b, c, d) 37 | 38 | puts soln.join("\t") 39 | end 40 | 41 | main 42 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/go/thomas.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "fmt" 4 | 5 | func thomas(a, b, c, d []float64) []float64 { 6 | c[0] = c[0] / b[0] 7 | d[0] = d[0] / b[0] 8 | 9 | for i := 1; i < len(d); i++ { 10 | scale := 1. / (b[i] - c[i-1]*a[i]) 11 | c[i] *= scale 12 | d[i] = (d[i] - a[i]*d[i-1]) * scale 13 | } 14 | 15 | for i := len(d) - 2; i >= 0; i-- { 16 | d[i] -= c[i] * d[i+1] 17 | } 18 | 19 | return d 20 | } 21 | 22 | func main() { 23 | a := []float64{0., 2., 3.} 24 | b := []float64{1., 3., 6.} 25 | c := []float64{4., 5., 0.} 26 | d := []float64{7., 5., 3.} 27 | 28 | fmt.Println("The system,") 29 | fmt.Println("[1.0 4.0 0.0][x] = [7.0]") 30 | fmt.Println("[2.0 3.0 5.0][y] = [5.0]") 31 | fmt.Println("[0.0 3.0 6.0][z] = [3.0]") 32 | fmt.Println("has the solution:") 33 | solve := thomas(a, b, c, d) 34 | for _, i := range solve { 35 | fmt.Printf("[%f]\n", i) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/haskell/thomas.hs: -------------------------------------------------------------------------------- 1 | import Data.List (zip4) 2 | import Data.Ratio 3 | 4 | thomas :: Fractional a => [a] -> [a] -> [a] -> [a] -> [a] 5 | thomas a b c = init . scanr back 0 . tail . scanl forward (0, 0) . zip4 a b c 6 | where 7 | forward (c', d') (a, b, c, d) = 8 | let denominator = b - a * c' 9 | in (c / denominator, (d - a * d') / denominator) 10 | back (c, d) x = d - c * x 11 | 12 | main :: IO () 13 | main = do 14 | let a = [0, 2, 3] :: [Ratio Int] 15 | b = [1, 3, 6] 16 | c = [4, 5, 0] 17 | d = [7, 5, 3] 18 | print $ thomas a b c d 19 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/javascript/thomas.js: -------------------------------------------------------------------------------- 1 | function thomas(a, b, c, x) { 2 | const y = []; 3 | 4 | y[0] = c[0] / b[0]; 5 | x[0] = x[0] / b[0]; 6 | 7 | for (let i = 1; i < a.length; i++) { 8 | const scale = 1.0 / (b[i] - a[i] * y[i - 1]); 9 | y[i] = c[i] * scale; 10 | x[i] = (x[i] - a[i] * x[i - 1]) * scale; 11 | } 12 | 13 | for (let i = a.length - 2; i >= 0; i--) 14 | x[i] -= y[i] * x[i + 1]; 15 | } 16 | 17 | let a = [0.0, 2.0, 3.0]; 18 | let b = [1.0, 3.0, 6.0]; 19 | let c = [4.0, 5.0, 0.0]; 20 | let x = [7.0, 5.0, 3.0]; 21 | 22 | console.log("The system,"); 23 | console.log("[1.0 4.0 0.0][x] = [7.0]"); 24 | console.log("[2.0 3.0 5.0][y] = [5.0]"); 25 | console.log("[0.0 3.0 6.0][z] = [3.0]"); 26 | console.log("has the solution:\n"); 27 | 28 | thomas(a, b, c, x); 29 | 30 | for (let i = 0; i < 3; i++) 31 | console.log("[" + x[i] + "]"); 32 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/julia/thomas.jl: -------------------------------------------------------------------------------- 1 | function thomas(a::Vector{Float64}, b::Vector{Float64}, c::Vector{Float64}, 2 | d::Vector{Float64}, n::Int64) 3 | 4 | x = copy(d) 5 | c_prime = copy(c) 6 | 7 | # Setting initial elements 8 | c_prime[1] /= b[1] 9 | x[1] /= b[1] 10 | 11 | for i = 2:n 12 | # Scale factor is for c_prime and x 13 | scale = 1.0 / (b[i] - c_prime[i-1]*a[i]) 14 | c_prime[i] *= scale 15 | x[i] = (x[i] - a[i] * x[i-1]) * scale 16 | end 17 | 18 | # Back-substitution 19 | for i = n-1:-1:1 20 | x[i] -= (c_prime[i] * x[i+1]) 21 | end 22 | 23 | return x 24 | 25 | end 26 | 27 | function main() 28 | a = [0.0, 2.0, 3.0] 29 | b = [1.0, 3.0, 6.0] 30 | c = [4.0, 5.0, 0.0] 31 | d = [7.0, 5.0, 3.0] 32 | 33 | println( 34 | """The system 35 | $(join((b[1], c[1], "", "|", d[1]), "\t")) 36 | $(join((a[2], b[2], c[2], "|", d[2]), "\t")) 37 | $(join(("", a[3], b[3], "|", d[3]), "\t")) 38 | Has the solution:""" 39 | ) 40 | 41 | soln = thomas(a, b, c, d, 3) 42 | 43 | println(soln) 44 | end 45 | 46 | main() 47 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/kotlin/thomas.kt: -------------------------------------------------------------------------------- 1 | private fun thomas(a: DoubleArray, b: DoubleArray, c: DoubleArray, d: DoubleArray): DoubleArray { 2 | val cPrime = c.clone() 3 | val x = d.clone() 4 | val size = a.size 5 | cPrime[0] /= b[0] 6 | x[0] /= b[0] 7 | for (i in 1 until size) { 8 | val scale = 1.0 / (b[i] - cPrime[i - 1] * a[i]) 9 | cPrime[i] *= scale 10 | x[i] = (x[i] - a[i] * x[i - 1]) * scale 11 | } 12 | for (i in (size - 2) downTo 0) { 13 | x[i] -= cPrime[i] * x[i + 1] 14 | } 15 | return x 16 | } 17 | 18 | fun main(args: Array) { 19 | val a = doubleArrayOf(0.0, 2.0, 3.0) 20 | val b = doubleArrayOf(1.0, 3.0, 6.0) 21 | val c = doubleArrayOf(4.0, 5.0, 0.0) 22 | val x = doubleArrayOf(7.0, 5.0, 3.0) 23 | val solution = thomas(a, b, c, x) 24 | 25 | println("System:") 26 | println("[%.1f, %.1f, %.1f][x] = [%.1f]".format(b[0], c[0], 0f, x[0])) 27 | println("[%.1f, %.1f, %.1f][y] = [%.1f]".format(a[1], b[1], c[1], x[1])) 28 | println("[%.1f, %.1f, %.1f][z] = [%.1f]\n".format(0f, a[2], b[2], x[2])) 29 | println("Solution:") 30 | for (i in solution.indices) { 31 | println("[% .5f]".format(solution[i])) 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/lua/thomas.lua: -------------------------------------------------------------------------------- 1 | local function thomas(a, b, c, d) 2 | 3 | -- Create tables and set initial elements 4 | local c_prime = {c[1] / b[1]} 5 | local result = {d[1] / b[1]} 6 | 7 | for i = 2, #a do 8 | -- Scale factor is for c_prime and result 9 | local scale = 1.0 / (b[i] - a[i] * c_prime[i - 1]) 10 | c_prime[i] = c[i] * scale 11 | result[i] = (d[i] - a[i] * result[i - 1]) * scale 12 | end 13 | 14 | -- Back-substitution 15 | for i = #a-1, 1, -1 do 16 | result[i] = result[i] - (c_prime[i] * result [i + 1]) 17 | end 18 | 19 | return result 20 | end 21 | 22 | local a = {0.0, 2.0, 3.0} 23 | local b = {1.0, 3.0, 6.0} 24 | local c = {4.0, 5.0, 0.0} 25 | local d = {7.0, 5.0, 3.0} 26 | 27 | print("The system") 28 | print(b[1], c[1], "", "|", d[1]) 29 | print(a[2], b[2], c[2], "|", d[2]) 30 | print("", a[3], b[3], "|", d[3]) 31 | print("Has the solution:") 32 | 33 | local solution = thomas(a, b, c, d) 34 | 35 | print(table.unpack(solution)) 36 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/nim/thomas_algorithm.nim: -------------------------------------------------------------------------------- 1 | proc thomas_algorithm(a, b, c_in, d_in: seq[float]): seq[float] = 2 | 3 | let n: int = len(d_in) 4 | 5 | var c: seq[float] = c_in 6 | var d: seq[float] = d_in 7 | 8 | c[0] /= b[0] 9 | d[0] /= b[0] 10 | 11 | for i in 1..n - 1: 12 | let scale: float = (1 / (b[i] - c[i - 1] * a[i])) 13 | 14 | c[i] *= scale 15 | d[i] = (d[i] - a[i] * d[i - 1]) * scale 16 | 17 | for i in countdown(n - 2,0): 18 | d[i] -= c[i] * d[i + 1] 19 | 20 | 21 | return d 22 | 23 | 24 | const x: seq[float] = @[0.0, 2.0, 3.0] 25 | const y: seq[float] = @[1.0, 3.0, 6.0] 26 | const z: seq[float] = @[4.0, 5.0, 0.0] 27 | const w: seq[float] = @[7.0, 5.0, 3.0] 28 | 29 | echo "The system," 30 | echo "[1.0 4.0 0.0][x] = [7.0]" 31 | echo "[2.0 3.0 5.0][y] = [5.0]" 32 | echo "[0.0 3.0 6.0][z] = [3.0]" 33 | 34 | echo "has the solution:" 35 | 36 | const soln: seq[float] = thomas_algorithm(x, y, z, w) 37 | 38 | for i in 0..len(w) - 1: 39 | echo soln[i] 40 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/php/thomas.php: -------------------------------------------------------------------------------- 1 | = 0; --$i) 17 | $x[$i] -= $y[$i] & $x[$i + 1]; 18 | 19 | return $x; 20 | } 21 | 22 | 23 | $a = [0.0, 2.0, 3.0]; 24 | $b = [1.0, 3.0, 6.0]; 25 | $c = [4.0, 5.0, 0.0]; 26 | $x = [7.0, 5.0, 3.0]; 27 | 28 | printf('The system,%s', PHP_EOL); 29 | printf(' [%s, %s, %s][x] = [%s]%s', $b[0], $c[0], 0, $x[0], PHP_EOL); 30 | printf(' [%s, %s, %s][y] = [%s]%s', $a[1], $b[1], $c[1], $x[1], PHP_EOL); 31 | printf(' [%s, %s, %s][z] = [%s]%s', 0, $a[2], $b[2], $x[2], PHP_EOL); 32 | printf('has the solution:%s', PHP_EOL); 33 | 34 | $solution = thomas_algorithm($a, $a, $c, $x, count($x)); 35 | for ($i = 0; $i < count($solution); $i++) 36 | printf(' [%s]%s', $solution[$i], PHP_EOL); 37 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/python/thomas.py: -------------------------------------------------------------------------------- 1 | # Author: gammison 2 | 3 | # note this example is inplace and destructive 4 | def thomas(a, b, c, d): 5 | 6 | # set the initial elements 7 | c[0] = c[0] / b[0] 8 | d[0] = d[0] / b[0] 9 | 10 | n = len(d) # number of equations to solve 11 | for i in range(1, n): 12 | # scale factor for c and d 13 | scale = 1 / (b[i] - c[i-1] * a[i]) 14 | 15 | c[i] *= scale 16 | d[i] = (d[i] - a[i] * d[i-1]) * scale 17 | 18 | 19 | # do the back substitution 20 | for i in range(n-2, -1, -1): 21 | d[i] -= c[i] * d[i+1] 22 | 23 | return d 24 | 25 | def main(): 26 | # example for matrix 27 | # [1 4 0][x] [7] 28 | # [2 3 5][y] = [5] 29 | # [0 3 6][z] [3] 30 | 31 | # [.8666] 32 | # soln will equal [1.533] 33 | # [-.266] 34 | # note we index a from 1 and c from 0 35 | a = [0, 2, 3] 36 | b = [1, 3, 6] 37 | c = [4, 5, 0] 38 | d = [7, 5, 3] 39 | 40 | soln = thomas(a, b, c, d) 41 | print(soln) 42 | 43 | if __name__ == '__main__': 44 | main() 45 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/ruby/thomas.rb: -------------------------------------------------------------------------------- 1 | # note this example is inplace and destructive 2 | def thomas(a, b, c, d) 3 | # set the initial elements 4 | c[0] = c[0] / b[0] 5 | d[0] = d[0] / b[0] 6 | 7 | n = d.length # number of equations to solve 8 | (1...n).each do |i| 9 | scale = 1 / (b[i] - c[i - 1] * a[i]) # scale factor for c and d 10 | c[i] *= scale 11 | d[i] = (d[i] - a[i] * d[i - 1]) * scale 12 | end 13 | 14 | # do the back substitution 15 | (n - 2).downto(0).each do |j| 16 | d[j] -= c[j] * d[j + 1] 17 | end 18 | 19 | d 20 | end 21 | 22 | # example for matrix 23 | # [1 4 0][x] [7] 24 | # [2 3 5][y] = [5] 25 | # [0 3 6][z] [3] 26 | 27 | # [.8666] 28 | # soln will equal [1.533] 29 | # [-.266] 30 | # note we index a from 1 and c from 0 31 | 32 | a = [0.0, 2.0, 3.0] 33 | b = [1.0, 3.0, 6.0] 34 | c = [4.0, 5.0, 0.0] 35 | d = [7.0, 5.0, 3.0] 36 | 37 | soln = thomas(a, b, c, d) 38 | puts soln 39 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/rust/thomas.rs: -------------------------------------------------------------------------------- 1 | fn thomas(a: &[f64], b: &[f64], c: &[f64], x: &[f64]) -> Vec { 2 | let size = a.len(); 3 | let mut y = vec![0.0; size]; 4 | let mut z = Vec::from(x); 5 | 6 | y[0] = c[0] / b[0]; 7 | z[0] = x[0] / b[0]; 8 | 9 | for i in 1..size { 10 | let scale = 1.0 / (b[i] - a[i] * y[i - 1]); 11 | y[i] = c[i] * scale; 12 | z[i] = (z[i] - a[i] * z[i - 1]) * scale; 13 | } 14 | 15 | for i in (0..(size - 1)).rev() { 16 | z[i] -= y[i] * z[i + 1]; 17 | } 18 | 19 | z 20 | } 21 | 22 | fn main() { 23 | let a = vec![0.0, 2.0, 3.0]; 24 | let b = vec![1.0, 3.0, 6.0]; 25 | let c = vec![4.0, 5.0, 0.0]; 26 | let x = vec![7.0, 5.0, 3.0]; 27 | 28 | println!("The system"); 29 | println!("[{:?} {:?} {:?}][x] = [{:?}]", a[0], b[0], c[0], &x[0]); 30 | println!("[{:?} {:?} {:?}][x] = [{:?}]", a[1], b[1], c[1], &x[1]); 31 | println!("[{:?} {:?} {:?}][x] = [{:?}]", a[2], b[2], c[2], &x[2]); 32 | println!("has the solution"); 33 | 34 | let y = thomas(&a, &b, &c, &x); 35 | 36 | y.iter() 37 | .for_each(|i| println!("[{:>19}]", format!("{:18}", format!("{:?}", i)))); 38 | } 39 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/scratch/thomas.txt: -------------------------------------------------------------------------------- 1 | define Solvetridiagonalsystem 2 | set [n v] to (length of [b v]) 3 | if > then 4 | replace item (1 v) of [c v] with ((item (1 v) of [c v]) / (item (1 v) of [b v])) 5 | replace item (1 v) of [d v] with ((item (1 v) of [d v]) / (item (1 v) of [b v])) 6 | end 7 | set [indx v] to (2) 8 | repeat ((n) - (1)) 9 | if > then 10 | replace item (indx) of [c v] with ((item (indx) of [c v]) / ((item (indx) of [b v]) - ((item (indx) of [a v]) * (item((indx) - (1)) of [c v])))) 11 | replace item (indx) of [d v] with (((item (indx) of [c v]) - ((item (indx) of [a v]) * (item ((indx) - (1)) of [d v]))) / ((item (indx) of [b v]) - ((item (indx) of [a v]) * (item ((indx) - (1)) of [c v]))) 12 | end 13 | change [indx v] by (1) 14 | end 15 | delete (all v) of [x v] 16 | add (item (last v) of [d v]) to [x v] 17 | set [indx v] to ((n) - (1)) 18 | repeat ((n) - (1)) 19 | insert ((item (indx) of [d v]) - ((item(indx) of [c v]) * (item (1 v) of [x v]))) at (1 v) of [x v] 20 | change [indx v] by (-1) 21 | end 22 | -------------------------------------------------------------------------------- /contents/thomas_algorithm/code/swift/thomas.swift: -------------------------------------------------------------------------------- 1 | func thomas(a: [Double], b: [Double], c: [Double], d: [Double]) -> [Double] { 2 | var a = a 3 | var b = b 4 | var c = c 5 | var d = d 6 | 7 | // set the initial elements 8 | c[0] = c[0] / b[0] 9 | d[0] = d[0] / b[0] 10 | 11 | let n = d.count // number of equations to solve 12 | for i in 1..= 0; i-- { 14 | new_d[i] -= new_c[i] * new_d[i+1] 15 | } 16 | 17 | return new_d 18 | } 19 | 20 | fn main() { 21 | a := [0.0, 2.0, 3.0] 22 | b := [1.0, 3.0, 6.0] 23 | c := [4.0, 5.0, 0.0] 24 | d := [7.0, 5.0, 3.0] 25 | 26 | println("The system,") 27 | println("[1.0 4.0 0.0][x] = [7.0]") 28 | println("[2.0 3.0 5.0][y] = [5.0]") 29 | println("[0.0 3.0 6.0][z] = [3.0]") 30 | println("has the solution:") 31 | solution := thomas(a, b, c, d) 32 | for i in solution { 33 | println("[$i]") 34 | } 35 | } -------------------------------------------------------------------------------- /contents/tree_traversal/code/csharp/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace TreeTraversal 4 | { 5 | class Program 6 | { 7 | static void Main(string[] args) 8 | { 9 | var tree = new Tree(2, 3); 10 | Console.WriteLine("[#]\nRecursive DFS:"); 11 | tree.DFSRecursive(); 12 | Console.WriteLine(); 13 | 14 | Console.WriteLine("[#]\nRecursive Postorder DFS:"); 15 | tree.DFSRecursivePostorder(); 16 | Console.WriteLine(); 17 | 18 | Console.WriteLine("[#]\nStack-based DFS:"); 19 | tree.DFSStack(); 20 | Console.WriteLine(); 21 | 22 | Console.WriteLine("[#]\nQueue-based BFS:"); 23 | tree.BFSQueue(); 24 | Console.WriteLine(); 25 | 26 | tree = new Tree(3, 2); 27 | Console.WriteLine("[#]\nRecursive Inorder DFS for Binary Tree:"); 28 | tree.DFSRecursiveInorderBinary(); 29 | Console.WriteLine(); 30 | } 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /contents/tree_traversal/code/csharp/code.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net5.0 6 | false 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /contents/tree_traversal/code/java/MainClass.java: -------------------------------------------------------------------------------- 1 | //submitted by xam4lor 2 | public class MainClass { 3 | public static void main(String[] args) { 4 | Tree tree = new Tree(2, 3); 5 | 6 | System.out.println("[#]\nRecursive DFS:"); 7 | tree.dfsRecursive(); 8 | System.out.println(); 9 | 10 | System.out.println("[#]\nRecursive Postorder DFS:"); 11 | tree.dfsRecursivePostOrder(); 12 | System.out.println(); 13 | 14 | 15 | System.out.println("[#]\nStack-based DFS:"); 16 | tree.dfsStack(); 17 | System.out.println(); 18 | 19 | 20 | System.out.println("[#]\nQueue-based BFS:"); 21 | tree.bfsQueue(); 22 | System.out.println(); 23 | 24 | 25 | // 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. 26 | //System.out.println("Using in-order binary recursive DFS : (fail)"); 27 | //tree.dfsRecursiveInOrderBinary(); 28 | 29 | tree = new Tree(3, 2); 30 | System.out.println("[#]\nRecursive Inorder DFS for Binary Tree:"); 31 | tree.dfsRecursiveInOrderBinary(); 32 | System.out.println(); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /contents/tree_traversal/res/3-tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/3-tree.png -------------------------------------------------------------------------------- /contents/tree_traversal/res/BFS_simple.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/BFS_simple.png -------------------------------------------------------------------------------- /contents/tree_traversal/res/DFS_in.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/DFS_in.png -------------------------------------------------------------------------------- /contents/tree_traversal/res/DFS_post.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/DFS_post.png -------------------------------------------------------------------------------- /contents/tree_traversal/res/DFS_pre.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/DFS_pre.png -------------------------------------------------------------------------------- /contents/tree_traversal/res/binary_tree.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/tree_traversal/res/binary_tree.png -------------------------------------------------------------------------------- /contents/verlet_integration/code/labview/verlet_labview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/verlet_integration/code/labview/verlet_labview.png -------------------------------------------------------------------------------- /contents/verlet_integration/code/matlab/verlet.m: -------------------------------------------------------------------------------- 1 | % Submitted by P. Mekhail 2 | % Parameters to change 3 | n = 400; % Number of steps 4 | x0 = 5; % Ball starting height(in metres) 5 | v0 = 0; % Ball starting velocity (+ive is up) 6 | dt = 0.01; % Time step (in seconds) 7 | eff = 0.4; % Ball efficency when bouncing 8 | A = @(x) -10; % Acceleration as a function of position 9 | bounce = 1; % Do you want the ball to bounce? 10 | 11 | % Making position and time vectors 12 | x = zeros(n,1); 13 | t = 0:dt:n*dt-dt; 14 | 15 | % Setting the initial conditions 16 | x(1) = x0; 17 | x(2) = x0 + v0*dt + 0.5*A(x0)*dt^2; 18 | 19 | % Runnin Verlet Integration 20 | for i = 2:n-1 21 | xnew = 2*x(i)-x(i-1)+A(x(i))*dt^2; 22 | if bounce 23 | if xnew > 0 24 | % If you haven't hit the ground keep going 25 | x(i+1) = xnew; 26 | else 27 | % If you have calculated velocity and invert its sign 28 | v = sqrt(eff)*(xnew-x(i-1))/(2*dt); 29 | x(i+1) = x(i) - v*dt + 0.5*A(x(i))*dt^2; 30 | end 31 | else 32 | x(i+1) = xnew; 33 | end 34 | end 35 | plot(t,x) 36 | title('Ball''s Trajectory') 37 | xlabel('Time (s)'); ylabel('Height (m)'); 38 | 39 | -------------------------------------------------------------------------------- /contents/verlet_integration/code/scratch/verlet_scratch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/contents/verlet_integration/code/scratch/verlet_scratch.png -------------------------------------------------------------------------------- /math.md: -------------------------------------------------------------------------------- 1 | 4 | $$ 5 | \newcommand{\d}{\mathrm{d}} 6 | \newcommand{\bff}{\boldsymbol{f}} 7 | \newcommand{\bfg}{\boldsymbol{g}} 8 | \newcommand{\bfp}{\boldsymbol{p}} 9 | \newcommand{\bfq}{\boldsymbol{q}} 10 | \newcommand{\bfx}{\boldsymbol{x}} 11 | \newcommand{\bfu}{\boldsymbol{u}} 12 | \newcommand{\bfv}{\boldsymbol{v}} 13 | \newcommand{\bfA}{\boldsymbol{A}} 14 | \newcommand{\bfB}{\boldsymbol{B}} 15 | \newcommand{\bfC}{\boldsymbol{C}} 16 | \newcommand{\bfM}{\boldsymbol{M}} 17 | \newcommand{\bfJ}{\boldsymbol{J}} 18 | \newcommand{\bfR}{\boldsymbol{R}} 19 | \newcommand{\bfT}{\boldsymbol{T}} 20 | \newcommand{\bfomega}{\boldsymbol{\omega}} 21 | \newcommand{\bftau}{\boldsymbol{\tau}} 22 | $$ 23 | 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "algorithm-archive", 3 | "description": "A collaborative book on algorithms", 4 | "version": "0.0.1", 5 | "maintainers": [ 6 | { 7 | "name": "James Schloss" 8 | } 9 | ], 10 | "dependencies": { 11 | "gitbook-plugin-api-language-selector": "git+https://github.com/algorithm-archivists/gitbook-plugin-api-language-selector.git", 12 | "gitbook-plugin-bibtex-cite": "git+https://github.com/algorithm-archivists/gitbook-plugin-bibtex-cite.git", 13 | "gitbook-plugin-bulk-redirect": "^0.2.1", 14 | "gitbook-plugin-ga": "^2.0.0", 15 | "gitbook-plugin-include-codeblock": "^3.2.2", 16 | "gitbook-plugin-mathjax": "git+https://github.com/algorithm-archivists/plugin-mathjax.git", 17 | "gitbook-plugin-prism": "^2.4.0", 18 | "gitbook-plugin-wordcount": "^0.0.1", 19 | "honkit": "^3.6.16" 20 | }, 21 | "repository": { 22 | "type": "git", 23 | "url": "https://github.com/algorithm-archivists/algorithm-archive.git" 24 | }, 25 | "license": "MIT", 26 | "scripts": { 27 | "build": "honkit build", 28 | "serve": "honkit serve" 29 | }, 30 | "homepage": "https://www.algorithm-archive.org/" 31 | } 32 | -------------------------------------------------------------------------------- /res/languages.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/leios/algorithm-archive/a3276bedd94ea7cee587bb565c351c405e9b86b9/res/languages.gif -------------------------------------------------------------------------------- /sconscripts/asm-x64_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile language env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | env.X64(f'#/build/{language}/{chapter_name}', str(file), LINKFLAGS='-no-pie') 7 | -------------------------------------------------------------------------------- /sconscripts/c_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | env.C(f'#/build/c/{chapter_name}', str(file)) 7 | -------------------------------------------------------------------------------- /sconscripts/cpp_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | env.CPlusPlus(f'#/build/cpp/{chapter_name}', str(file)) 7 | -------------------------------------------------------------------------------- /sconscripts/fortran_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | env.Fortran(f'#/build/fortran/{chapter_name}', str(file)) 7 | -------------------------------------------------------------------------------- /sconscripts/go_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | env.Go(f'#/build/go/{chapter_name}', str(file)) 7 | -------------------------------------------------------------------------------- /sconscripts/rust_SConscript: -------------------------------------------------------------------------------- 1 | Import('files_to_compile env') 2 | from pathlib import Path 3 | 4 | for file in files_to_compile: 5 | chapter_name = file.parent.parent.parent.stem 6 | if (file.parent / 'Cargo.toml').exists(): 7 | env.cargo(target=f'#/build/rust/{chapter_name}', 8 | source=str(file), 9 | MANIFEST=str(file.parent / 'Cargo.toml'), 10 | SOURCE_DIR=str(file.parent)) 11 | env.Clean('rust', str(file.parent / 'target')) 12 | else: 13 | env.rustc(f'#/build/rust/{chapter_name}', str(file)) 14 | env.Clean('rust', f'#/build/rust/{chapter_name}.pdb') 15 | -------------------------------------------------------------------------------- /styles/website.css: -------------------------------------------------------------------------------- 1 | .book .book-body .page-wrapper .page-inner section.normal .hljs-meta-keyword { 2 | color: #8959a8; 3 | } 4 | 5 | .book .book-body .page-wrapper .page-inner section.normal .hljs-meta-string { 6 | color: #718c00; 7 | } 8 | 9 | .book .book-body .page-wrapper { 10 | margin-bottom: 12em; 11 | } 12 | 13 | img.center { 14 | display: block; 15 | margin-left: auto; 16 | margin-right: auto; 17 | } 18 | 19 | .search-results-item p{ 20 | color: #4183C4; 21 | } 22 | 23 | #book-search-results .search-results .has-results .search-results-item a { 24 | color: #777; 25 | } 26 | 27 | 28 | #book-search-input input, #book-search-input input:focus, #book-search-input input:hover{ 29 | color: #222; 30 | } 31 | 32 | @media print { 33 | /* Hide side bar */ 34 | .book-summary { 35 | display: none; 36 | } 37 | 38 | /*Hide top bar*/ 39 | .book-header { 40 | display: none; 41 | } 42 | 43 | /*Hide left and right navigation arrows*/ 44 | .navigation { 45 | display: none; 46 | } 47 | 48 | /*Make sure all content is displayed and not just the first page*/ 49 | .book-body { 50 | position: static; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /tools/cleanup/clean_book_json.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Sorts languages in book.json alphabetically into book.json_. 4 | Check the file manually, then rename. 5 | You need to pass the path to the file as an argument. 6 | From root: $ tools/cleanup/clean_book_json.py book.json 7 | """ 8 | 9 | import json 10 | import sys 11 | 12 | path = sys.argv[1] 13 | 14 | with open(path) as f: 15 | text = f.read() 16 | 17 | book = json.loads(text) 18 | book["pluginsConfig"]["api-language-selector"]["languages"]\ 19 | .sort(key=lambda x: x[u'name'].lower()) 20 | 21 | with open(path + "_", "w") as f: 22 | f.write(json.dumps(book, indent=2)) 23 | -------------------------------------------------------------------------------- /tools/cleanup/clean_editorconfig.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | """ 3 | Sorts languages in .editorconfig alphabetically into .editorconfig_. 4 | Check the file manually, then rename. 5 | You need to pass the path to the file as an argument. 6 | From root: $ tools/cleanup/clean_editorconfig.py .editorconfig 7 | Known examples of bug: 8 | - Language tag with missing space: "#Lua" instead of "# Lua" 9 | """ 10 | 11 | import sys 12 | 13 | path = sys.argv[1] 14 | 15 | with open(path) as f: 16 | config = f.read() 17 | 18 | lang = config.split("\n#") 19 | lang_sorted = lang[0:2] + sorted(lang[2:], key = lambda x : x.lower()) 20 | config = "\n#".join(lang_sorted) 21 | 22 | with open(path + "_", "w") as f: 23 | f.write(config) 24 | -------------------------------------------------------------------------------- /tools/hooks/README.md: -------------------------------------------------------------------------------- 1 | # Git Hooks 2 | 3 | These are scripts executed by Git at specific steps of the version control workflow, depending on their name. 4 | 5 | - `pre-commit` runs before attempting to commit, and prevents committing to the local master branch. 6 | 7 | To install, 8 | ```bash 9 | $ ./install_hooks.bash 10 | ``` 11 | 12 | To read more about hooks, read the [Pro Git chapter](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks). 13 | -------------------------------------------------------------------------------- /tools/hooks/install_hooks.bash: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -o errexit 4 | 5 | # Grab the directory of _this_ script. 6 | SCRIPTDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" 7 | PROJECTDIR="$(realpath "${SCRIPTDIR}"/../..)" 8 | 9 | # Try to link each hook into the project's .git/hooks directory. 10 | for hook in $(ls "${SCRIPTDIR}"/*.hook); do 11 | stub="${hook%.*}" 12 | dest="${PROJECTDIR}/.git/hooks/$(basename ${stub})" 13 | ln -sv "${hook}" "${dest}" 14 | done 15 | -------------------------------------------------------------------------------- /tools/hooks/pre-commit.hook: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | # prevent commit to local master branch 4 | # taken from https://gist.github.com/aaronhoffman/ffbfd36928f9336be2436cffe39feaec#file-pre-commit 5 | 6 | branch=`git symbolic-ref HEAD` 7 | if [ "$branch" = "refs/heads/master" ]; then 8 | echo "pre-commit hook: Cannot commit to the local master branch." 9 | echo "Please make all your changes in a new feature branch:" 10 | echo "$ git checkout -b my-new-feature-branch" 11 | exit 1 12 | fi 13 | 14 | exit 0 15 | --------------------------------------------------------------------------------