From 633b36288a3761e4593b65ff9b657c7662250299 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ingy=20d=C3=B6t=20Net?= Date: Tue, 18 Jul 2023 13:51:12 -0700 Subject: [PATCH] Data Update --- Lang/ALGOL-68/FASTA-format | 1 + Lang/ALGOL-68/Next-highest-int-from-digits | 1 + Lang/ALGOL-W/00-LANG.txt | 3 + ...ts-of-the-product-of-their-proper-divisors | 1 + .../Horizontal-sundial-calculations | 1 + Lang/ANSI-BASIC/Largest-proper-divisor-of-n | 1 + Lang/ANSI-BASIC/Nth | 1 + Lang/ARM-Assembly/Averages-Median | 1 + Lang/ATS/Determine-if-two-triangles-overlap | 1 + Lang/AutoHotkey/ASCII-art-diagram-converter | 1 + Lang/C++/00-LANG.txt | 2 +- Lang/C++/B-zier-curves-Intersections | 1 + Lang/C++/Deconvolution-1D | 1 + Lang/C++/Demings-funnel | 1 + Lang/C++/Determine-sentence-type | 1 + Lang/C++/Distance-and-Bearing | 1 + Lang/C++/EKG-sequence-convergence | 1 + Lang/C++/Pisano-period | 1 + ...tors-whose-factors-are-all-substrings-of-k | 1 + Lang/Craft-Basic/Harmonic-series | 1 + Lang/Craft-Basic/Largest-proper-divisor-of-n | 1 + Lang/EMal/Comments | 1 + Lang/EMal/Enumerations | 1 + Lang/EMal/Filter | 1 + Lang/EMal/Hash-from-two-arrays | 1 + Lang/EMal/Inheritance-Single | 1 + Lang/EMal/String-prepend | 1 + Lang/F-Sharp/Minkowski-question-mark-function | 1 + ...ficient-and-perfect-number-classifications | 1 + Lang/FreeBASIC/Canonicalize-CIDR | 1 + Lang/FreeBASIC/Nautical-bell | 1 + Lang/J/Sum-and-product-puzzle | 1 + Lang/Java/15-puzzle-solver | 1 + Lang/Java/B-zier-curves-Intersections | 1 + Lang/Java/Color-quantization | 1 + Lang/Java/Compile-time-calculation | 1 + ...tors-whose-factors-are-all-substrings-of-k | 1 + ...s-with-ascending-or-descending-differences | 1 + Lang/Java/Curzon-numbers | 1 + Lang/Java/Deceptive-numbers | 1 + Lang/Java/Descending-primes | 1 + Lang/Java/Determine-sentence-type | 1 + Lang/Java/Duffinian-numbers | 1 + Lang/Jq/Old-Russian-measure-of-length | 1 + Lang/Lua/00-LANG.txt | 356 +------------ Lang/Lua/Factorial-primes | 1 + Lang/Lua/Particle-fountain | 1 + .../Last-Friday-of-each-month | 1 + Lang/Maxima/Attractive-numbers | 1 + Lang/MiniScript/Anti-primes | 1 + Lang/Modula-2/Trabb-Pardo-Knuth-algorithm | 1 + Lang/Odin/Anti-primes | 1 + Lang/Odin/Fibonacci-sequence | 1 + Lang/Odin/Pseudo-random-numbers-Splitmix64 | 1 + Lang/PL-M/FASTA-format | 1 + Lang/Palo-Alto-Tiny-BASIC/00-LANG.txt | 12 + ...ficient-and-perfect-number-classifications | 1 - Lang/QBasic/Canonicalize-CIDR | 1 + Lang/Rust/Arithmetic-derivative | 1 + Lang/Rust/Cistercian-numerals | 1 + Lang/Rust/Colorful-numbers | 1 + ...tors-whose-factors-are-all-substrings-of-k | 1 + Lang/Rust/Dinesmans-multiple-dwelling-problem | 1 + Lang/Rust/Modified-random-distribution | 1 + Lang/Rust/Sum-and-product-puzzle | 1 + Lang/S-BASIC/Array-length | 1 + Lang/Sidef/00-LANG.txt | 6 +- Lang/Sidef/Factorial-primes | 1 + Lang/Tcl/Harmonic-series | 1 + ...Pseudo-random-numbers-Middle-square-method | 1 + Lang/Transact-SQL/Julia-set | 1 + .../Java/15-puzzle-solver.java | 143 +++++ Task/24-game/Elena/24-game.elena | 66 +-- .../Elena/99-bottles-of-beer.elena | 4 +- Task/A+B/Elena/a+b-2.elena | 2 +- .../ascii-art-diagram-converter.ahk | 59 +++ ...ent-and-perfect-number-classifications.pas | 49 ++ ...ent-and-perfect-number-classifications.pas | 214 -------- Task/Anti-primes/ALGOL-68/anti-primes.alg | 27 +- .../{anti-primes.lua => anti-primes-1.lua} | 0 Task/Anti-primes/Lua/anti-primes-2.lua | 29 ++ Task/Anti-primes/MiniScript/anti-primes.mini | 33 ++ Task/Anti-primes/Odin/anti-primes.odin | 42 ++ .../{anti-primes.ring => anti-primes-1.ring} | 0 Task/Anti-primes/Ring/anti-primes-2.ring | 36 ++ Task/Anti-primes/Ruby/anti-primes.rb | 2 +- ...bitrary-precision-integers-included-.sidef | 6 +- .../Rust/arithmetic-derivative.rust | 25 + Task/Array-length/S-BASIC/array-length.basic | 13 + Task/Ascending-primes/00-TASK.txt | 1 + .../Maxima/attractive-numbers.maxima | 7 + .../ARM-Assembly/averages-median.arm | 493 ++++++++++++++++++ .../C++/b-zier-curves-intersections.cpp | 133 +++++ .../Java/b-zier-curves-intersections.java | 145 ++++++ Task/Caesar-cipher/REXX/caesar-cipher-1.rexx | 57 +- Task/Caesar-cipher/REXX/caesar-cipher-2.rexx | 61 ++- .../FreeBASIC/canonicalize-cidr.basic | 54 ++ .../QBasic/canonicalize-cidr.basic | 44 ++ .../Rust/cistercian-numerals.rust | 150 ++++++ .../Java/color-quantization.java | 127 +++++ .../Colorful-numbers/C++/colorful-numbers.cpp | 4 +- .../Rust/colorful-numbers.rust | 73 +++ .../Sidef/comma-quibbling.sidef | 4 +- Task/Comments/EMal/comments.emal | 9 + .../Java/compile-time-calculation.java | 9 + .../Raku/compile-time-calculation-2.raku | 2 +- ...rs-whose-factors-are-all-substrings-of-k.c | 44 ++ ...whose-factors-are-all-substrings-of-k.java | 74 +++ ...whose-factors-are-all-substrings-of-k.rust | 25 + .../Ol/conditional-structures-1.ol | 6 +- .../Ol/conditional-structures-2.ol | 11 +- .../Ol/conditional-structures-3.ol | 18 +- .../Ol/conditional-structures-4.ol | 33 +- .../Ol/conditional-structures-5.ol | 31 +- ...h-ascending-or-descending-differences.java | 86 +++ Task/Curzon-numbers/Java/curzon-numbers.java | 48 ++ .../{death-star.java => death-star-1.java} | 0 Task/Death-Star/Java/death-star-2.java | 125 +++++ .../Java/deceptive-numbers.java | 42 ++ .../Deconvolution-1D/C++/deconvolution-1d.cpp | 37 ++ Task/Demings-funnel/C++/demings-funnel.cpp | 76 +++ .../Java/descending-primes.java | 48 ++ .../determine-if-two-triangles-overlap.ats | 341 ++++++++++++ .../determine-if-two-triangles-overlap.rexx | 50 +- .../C++/determine-sentence-type.cpp | 31 ++ .../Java/determine-sentence-type.java | 30 ++ .../Sidef/dice-game-probabilities.sidef | 6 +- .../dinesmans-multiple-dwelling-problem.rust | 18 + ...inesmans-multiple-dwelling-problem-1.sidef | 2 +- .../C++/distance-and-bearing.cpp | 109 ++++ .../Java/duffinian-numbers.java | 61 +++ .../C++/ekg-sequence-convergence.cpp | 59 +++ Task/Enumerations/EMal/enumerations.emal | 22 + .../Sidef/executable-library-1.sidef | 10 +- Task/FASTA-format/ALGOL-68/fasta-format.alg | 22 + Task/FASTA-format/PL-M/fasta-format.plm | 97 ++++ .../ALGOL-68/factorial-primes.alg | 31 +- .../Factorial-primes/Lua/factorial-primes.lua | 39 ++ .../Sidef/factorial-primes.sidef | 14 + .../fibonacci-n-step-number-sequences-1.sidef | 2 +- .../Odin/fibonacci-sequence.odin | 22 + Task/Filter/EMal/filter.emal | 1 + Task/FizzBuzz/Sidef/fizzbuzz-3.sidef | 2 +- Task/FizzBuzz/Swift/fizzbuzz-3.swift | 28 + Task/Fractran/Julia/fractran.julia | 24 +- .../Sidef/greatest-subsequential-sum.sidef | 24 +- .../Craft-Basic/harmonic-series.basic | 34 ++ Task/Harmonic-series/Tcl/harmonic-series.tcl | 30 ++ .../EMal/hash-from-two-arrays.emal | 4 + .../Sidef/hofstadter-q-sequence-2.sidef | 4 +- .../horizontal-sundial-calculations.basic | 18 + ...ers-rule-for-polynomial-evaluation-2.sidef | 7 +- .../EMal/inheritance-single.emal | 16 + Task/Julia-set/Transact-SQL/julia-set.sql | 113 ++++ .../largest-proper-divisor-of-n.basic | 14 + .../largest-proper-divisor-of-n.basic | 25 + .../last-friday-of-each-month.m2000 | 24 + .../levenshtein-distance-alignment.sidef | 4 +- .../Sidef/levenshtein-distance-1.sidef | 4 +- .../Sidef/longest-common-subsequence.sidef | 12 +- .../Sidef/md5-implementation.sidef | 2 +- .../Julia/mandelbrot-set-4.julia | 34 +- .../Mandelbrot-set/Python/mandelbrot-set-5.py | 34 +- .../Sidef/mian-chowla-sequence.sidef | 14 +- .../Sidef/middle-three-digits.sidef | 8 +- .../minkowski-question-mark-function.fs | 13 + .../Rust/modified-random-distribution.rust | 29 ++ .../11l/multiplicative-order.11l | 4 +- .../Maxima/n-queens-problem-2.maxima | 10 +- .../Prolog/narcissistic-decimal-number.pro | 8 +- .../FreeBASIC/nautical-bell.basic | 18 + .../ALGOL-68/next-highest-int-from-digits.alg | 66 +++ Task/Nth/ANSI-BASIC/nth.basic | 28 + ...f-the-product-of-their-proper-divisors.alg | 39 ++ .../Jq/old-russian-measure-of-length.jq | 70 +++ .../Sidef/ordered-partitions.sidef | 2 +- .../Sidef/palindrome-detection-1.sidef | 2 +- .../Sidef/palindrome-detection-3.sidef | 4 +- .../Lua/particle-fountain.lua | 38 ++ .../11l/pernicious-numbers.11l | 7 +- Task/Pisano-period/C++/pisano-period.cpp | 138 +++++ .../Population-count/11l/population-count.11l | 7 +- ...ocate-descendants-to-their-ancestors.sidef | 2 +- .../Sidef/proper-divisors.sidef | 2 +- ...do-random-numbers-middle-square-method.tcl | 15 + .../pseudo-random-numbers-splitmix64.odin | 42 ++ ...-douglas-peucker-line-simplification.sidef | 10 +- .../Sidef/sorting-algorithms-bogosort.sidef | 16 +- .../sorting-algorithms-selection-sort.fs | 4 +- Task/Soundex/Sidef/soundex.sidef | 2 +- Task/String-prepend/EMal/string-prepend.emal | 6 + .../J/sum-and-product-puzzle-1.j | 20 + .../J/sum-and-product-puzzle-2.j | 34 ++ .../J/sum-and-product-puzzle-3.j | 10 + .../Rust/sum-and-product-puzzle.rust | 53 ++ Task/Thue-Morse/11l/thue-morse.11l | 2 +- .../Modula-2/trabb-pardo-knuth-algorithm.mod2 | 72 +++ .../Sidef/van-eck-sequence.sidef | 2 +- ...stribution-uniformity-chi-squared-test.cpp | 2 +- .../Applesoft-BASIC/war-card-game-1.basic | 125 +++-- .../Applesoft-BASIC/war-card-game-2.basic | 2 +- Task/Weird-numbers/Sidef/weird-numbers.sidef | 4 +- Task/Wireworld/Raku/wireworld.raku | 41 +- Task/Wireworld/Sidef/wireworld.sidef | 24 +- Task/Word-wrap/Sidef/word-wrap-1.sidef | 24 +- Task/Word-wrap/Sidef/word-wrap-2.sidef | 12 +- 206 files changed, 4762 insertions(+), 965 deletions(-) create mode 120000 Lang/ALGOL-68/FASTA-format create mode 120000 Lang/ALGOL-68/Next-highest-int-from-digits create mode 120000 Lang/ALGOL-W/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors create mode 120000 Lang/ANSI-BASIC/Horizontal-sundial-calculations create mode 120000 Lang/ANSI-BASIC/Largest-proper-divisor-of-n create mode 120000 Lang/ANSI-BASIC/Nth create mode 120000 Lang/ARM-Assembly/Averages-Median create mode 120000 Lang/ATS/Determine-if-two-triangles-overlap create mode 120000 Lang/AutoHotkey/ASCII-art-diagram-converter create mode 120000 Lang/C++/B-zier-curves-Intersections create mode 120000 Lang/C++/Deconvolution-1D create mode 120000 Lang/C++/Demings-funnel create mode 120000 Lang/C++/Determine-sentence-type create mode 120000 Lang/C++/Distance-and-Bearing create mode 120000 Lang/C++/EKG-sequence-convergence create mode 120000 Lang/C++/Pisano-period create mode 120000 Lang/C/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k create mode 120000 Lang/Craft-Basic/Harmonic-series create mode 120000 Lang/Craft-Basic/Largest-proper-divisor-of-n create mode 120000 Lang/EMal/Comments create mode 120000 Lang/EMal/Enumerations create mode 120000 Lang/EMal/Filter create mode 120000 Lang/EMal/Hash-from-two-arrays create mode 120000 Lang/EMal/Inheritance-Single create mode 120000 Lang/EMal/String-prepend create mode 120000 Lang/F-Sharp/Minkowski-question-mark-function create mode 120000 Lang/Free-Pascal-Lazarus/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/FreeBASIC/Canonicalize-CIDR create mode 120000 Lang/FreeBASIC/Nautical-bell create mode 120000 Lang/J/Sum-and-product-puzzle create mode 120000 Lang/Java/15-puzzle-solver create mode 120000 Lang/Java/B-zier-curves-Intersections create mode 120000 Lang/Java/Color-quantization create mode 120000 Lang/Java/Compile-time-calculation create mode 120000 Lang/Java/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k create mode 120000 Lang/Java/Consecutive-primes-with-ascending-or-descending-differences create mode 120000 Lang/Java/Curzon-numbers create mode 120000 Lang/Java/Deceptive-numbers create mode 120000 Lang/Java/Descending-primes create mode 120000 Lang/Java/Determine-sentence-type create mode 120000 Lang/Java/Duffinian-numbers create mode 120000 Lang/Jq/Old-Russian-measure-of-length create mode 120000 Lang/Lua/Factorial-primes create mode 120000 Lang/Lua/Particle-fountain create mode 120000 Lang/M2000-Interpreter/Last-Friday-of-each-month create mode 120000 Lang/Maxima/Attractive-numbers create mode 120000 Lang/MiniScript/Anti-primes create mode 120000 Lang/Modula-2/Trabb-Pardo-Knuth-algorithm create mode 120000 Lang/Odin/Anti-primes create mode 120000 Lang/Odin/Fibonacci-sequence create mode 120000 Lang/Odin/Pseudo-random-numbers-Splitmix64 create mode 120000 Lang/PL-M/FASTA-format delete mode 120000 Lang/Pascal/Abundant-deficient-and-perfect-number-classifications create mode 120000 Lang/QBasic/Canonicalize-CIDR create mode 120000 Lang/Rust/Arithmetic-derivative create mode 120000 Lang/Rust/Cistercian-numerals create mode 120000 Lang/Rust/Colorful-numbers create mode 120000 Lang/Rust/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k create mode 120000 Lang/Rust/Dinesmans-multiple-dwelling-problem create mode 120000 Lang/Rust/Modified-random-distribution create mode 120000 Lang/Rust/Sum-and-product-puzzle create mode 120000 Lang/S-BASIC/Array-length create mode 120000 Lang/Sidef/Factorial-primes create mode 120000 Lang/Tcl/Harmonic-series create mode 120000 Lang/Tcl/Pseudo-random-numbers-Middle-square-method create mode 120000 Lang/Transact-SQL/Julia-set create mode 100644 Task/15-puzzle-solver/Java/15-puzzle-solver.java create mode 100644 Task/ASCII-art-diagram-converter/AutoHotkey/ascii-art-diagram-converter.ahk create mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus/abundant-deficient-and-perfect-number-classifications.pas delete mode 100644 Task/Abundant-deficient-and-perfect-number-classifications/Pascal/abundant-deficient-and-perfect-number-classifications.pas rename Task/Anti-primes/Lua/{anti-primes.lua => anti-primes-1.lua} (100%) create mode 100644 Task/Anti-primes/Lua/anti-primes-2.lua create mode 100644 Task/Anti-primes/MiniScript/anti-primes.mini create mode 100644 Task/Anti-primes/Odin/anti-primes.odin rename Task/Anti-primes/Ring/{anti-primes.ring => anti-primes-1.ring} (100%) create mode 100644 Task/Anti-primes/Ring/anti-primes-2.ring create mode 100644 Task/Arithmetic-derivative/Rust/arithmetic-derivative.rust create mode 100644 Task/Array-length/S-BASIC/array-length.basic create mode 100644 Task/Attractive-numbers/Maxima/attractive-numbers.maxima create mode 100644 Task/Averages-Median/ARM-Assembly/averages-median.arm create mode 100644 Task/B-zier-curves-Intersections/C++/b-zier-curves-intersections.cpp create mode 100644 Task/B-zier-curves-Intersections/Java/b-zier-curves-intersections.java create mode 100644 Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic create mode 100644 Task/Canonicalize-CIDR/QBasic/canonicalize-cidr.basic create mode 100644 Task/Cistercian-numerals/Rust/cistercian-numerals.rust create mode 100644 Task/Color-quantization/Java/color-quantization.java create mode 100644 Task/Colorful-numbers/Rust/colorful-numbers.rust create mode 100644 Task/Comments/EMal/comments.emal create mode 100644 Task/Compile-time-calculation/Java/compile-time-calculation.java create mode 100644 Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.c create mode 100644 Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java create mode 100644 Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.rust create mode 100644 Task/Consecutive-primes-with-ascending-or-descending-differences/Java/consecutive-primes-with-ascending-or-descending-differences.java create mode 100644 Task/Curzon-numbers/Java/curzon-numbers.java rename Task/Death-Star/Java/{death-star.java => death-star-1.java} (100%) create mode 100644 Task/Death-Star/Java/death-star-2.java create mode 100644 Task/Deceptive-numbers/Java/deceptive-numbers.java create mode 100644 Task/Deconvolution-1D/C++/deconvolution-1d.cpp create mode 100644 Task/Demings-funnel/C++/demings-funnel.cpp create mode 100644 Task/Descending-primes/Java/descending-primes.java create mode 100644 Task/Determine-if-two-triangles-overlap/ATS/determine-if-two-triangles-overlap.ats create mode 100644 Task/Determine-sentence-type/C++/determine-sentence-type.cpp create mode 100644 Task/Determine-sentence-type/Java/determine-sentence-type.java create mode 100644 Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust create mode 100644 Task/Distance-and-Bearing/C++/distance-and-bearing.cpp create mode 100644 Task/Duffinian-numbers/Java/duffinian-numbers.java create mode 100644 Task/EKG-sequence-convergence/C++/ekg-sequence-convergence.cpp create mode 100644 Task/Enumerations/EMal/enumerations.emal create mode 100644 Task/FASTA-format/ALGOL-68/fasta-format.alg create mode 100644 Task/FASTA-format/PL-M/fasta-format.plm create mode 100644 Task/Factorial-primes/Lua/factorial-primes.lua create mode 100644 Task/Factorial-primes/Sidef/factorial-primes.sidef create mode 100644 Task/Fibonacci-sequence/Odin/fibonacci-sequence.odin create mode 100644 Task/Filter/EMal/filter.emal create mode 100644 Task/FizzBuzz/Swift/fizzbuzz-3.swift create mode 100644 Task/Harmonic-series/Craft-Basic/harmonic-series.basic create mode 100644 Task/Harmonic-series/Tcl/harmonic-series.tcl create mode 100644 Task/Hash-from-two-arrays/EMal/hash-from-two-arrays.emal create mode 100644 Task/Horizontal-sundial-calculations/ANSI-BASIC/horizontal-sundial-calculations.basic create mode 100644 Task/Inheritance-Single/EMal/inheritance-single.emal create mode 100644 Task/Julia-set/Transact-SQL/julia-set.sql create mode 100644 Task/Largest-proper-divisor-of-n/ANSI-BASIC/largest-proper-divisor-of-n.basic create mode 100644 Task/Largest-proper-divisor-of-n/Craft-Basic/largest-proper-divisor-of-n.basic create mode 100644 Task/Last-Friday-of-each-month/M2000-Interpreter/last-friday-of-each-month.m2000 create mode 100644 Task/Minkowski-question-mark-function/F-Sharp/minkowski-question-mark-function.fs create mode 100644 Task/Modified-random-distribution/Rust/modified-random-distribution.rust create mode 100644 Task/Nautical-bell/FreeBASIC/nautical-bell.basic create mode 100644 Task/Next-highest-int-from-digits/ALGOL-68/next-highest-int-from-digits.alg create mode 100644 Task/Nth/ANSI-BASIC/nth.basic create mode 100644 Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.alg create mode 100644 Task/Old-Russian-measure-of-length/Jq/old-russian-measure-of-length.jq create mode 100644 Task/Particle-fountain/Lua/particle-fountain.lua create mode 100644 Task/Pisano-period/C++/pisano-period.cpp create mode 100644 Task/Pseudo-random-numbers-Middle-square-method/Tcl/pseudo-random-numbers-middle-square-method.tcl create mode 100644 Task/Pseudo-random-numbers-Splitmix64/Odin/pseudo-random-numbers-splitmix64.odin create mode 100644 Task/String-prepend/EMal/string-prepend.emal create mode 100644 Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-1.j create mode 100644 Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-2.j create mode 100644 Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-3.j create mode 100644 Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rust create mode 100644 Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 diff --git a/Lang/ALGOL-68/FASTA-format b/Lang/ALGOL-68/FASTA-format new file mode 120000 index 0000000000..6951549e47 --- /dev/null +++ b/Lang/ALGOL-68/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-68/Next-highest-int-from-digits b/Lang/ALGOL-68/Next-highest-int-from-digits new file mode 120000 index 0000000000..7e6acab659 --- /dev/null +++ b/Lang/ALGOL-68/Next-highest-int-from-digits @@ -0,0 +1 @@ +../../Task/Next-highest-int-from-digits/ALGOL-68 \ No newline at end of file diff --git a/Lang/ALGOL-W/00-LANG.txt b/Lang/ALGOL-W/00-LANG.txt index 7d04034cdb..eed21ba5cf 100644 --- a/Lang/ALGOL-W/00-LANG.txt +++ b/Lang/ALGOL-W/00-LANG.txt @@ -28,6 +28,9 @@ Awe correctly compiles Tony Marsland's computer [[wp:chess|chess]] player and Hendrik Boom's [http://mtn-host.prjek.net/projects/a68h/ A68H] [[Algol 68]] compiler. +==To do== +[[Tasks not implemented in ALGOL W]] + ==See also== *[[wp:ALGOL_W|Algol W on Wikipedia]] *[[ALGOL 60]] diff --git a/Lang/ALGOL-W/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors b/Lang/ALGOL-W/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors new file mode 120000 index 0000000000..19db81f6ed --- /dev/null +++ b/Lang/ALGOL-W/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors @@ -0,0 +1 @@ +../../Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Horizontal-sundial-calculations b/Lang/ANSI-BASIC/Horizontal-sundial-calculations new file mode 120000 index 0000000000..9ac1ff4a6b --- /dev/null +++ b/Lang/ANSI-BASIC/Horizontal-sundial-calculations @@ -0,0 +1 @@ +../../Task/Horizontal-sundial-calculations/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Largest-proper-divisor-of-n b/Lang/ANSI-BASIC/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..e505793222 --- /dev/null +++ b/Lang/ANSI-BASIC/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ANSI-BASIC/Nth b/Lang/ANSI-BASIC/Nth new file mode 120000 index 0000000000..83517d5111 --- /dev/null +++ b/Lang/ANSI-BASIC/Nth @@ -0,0 +1 @@ +../../Task/Nth/ANSI-BASIC \ No newline at end of file diff --git a/Lang/ARM-Assembly/Averages-Median b/Lang/ARM-Assembly/Averages-Median new file mode 120000 index 0000000000..c20d36fae7 --- /dev/null +++ b/Lang/ARM-Assembly/Averages-Median @@ -0,0 +1 @@ +../../Task/Averages-Median/ARM-Assembly \ No newline at end of file diff --git a/Lang/ATS/Determine-if-two-triangles-overlap b/Lang/ATS/Determine-if-two-triangles-overlap new file mode 120000 index 0000000000..68e5e730ef --- /dev/null +++ b/Lang/ATS/Determine-if-two-triangles-overlap @@ -0,0 +1 @@ +../../Task/Determine-if-two-triangles-overlap/ATS \ No newline at end of file diff --git a/Lang/AutoHotkey/ASCII-art-diagram-converter b/Lang/AutoHotkey/ASCII-art-diagram-converter new file mode 120000 index 0000000000..fe014a6bf3 --- /dev/null +++ b/Lang/AutoHotkey/ASCII-art-diagram-converter @@ -0,0 +1 @@ +../../Task/ASCII-art-diagram-converter/AutoHotkey \ No newline at end of file diff --git a/Lang/C++/00-LANG.txt b/Lang/C++/00-LANG.txt index f5d2924ed6..5bd73a99aa 100644 --- a/Lang/C++/00-LANG.txt +++ b/Lang/C++/00-LANG.txt @@ -12,7 +12,7 @@ |LCT=yes |bnf=http://cpp.comsci.us/syntax/statement/index.html}}{{codepad}}{{allows|Network access}}{{allows|Database access }}{{allows|Concurrency}}{{provides|Run time polymorphism}}{{provides|Compile time polymorphism}}{{allows|Windowing UI}}{{allows|Graphics}}{{allows|OpenGL}}{{allows|Dynamic linking}}{{provides|File access}}{{allows|File system access}}{{provides|Objects}}{{allows|Signal handling}}{{provides|Mutable state}} -'''C++''' is named after the [[derived from::compatible with::C]] language, from which it is derived. C++ extends C into an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]]. +'''C++''' is named after the C language, from which it is derived. C++ extends C into an [[object-oriented language]]. However, unlike other object-oriented languages, it doesn't try to force you into [[object-oriented programming]], but is a multi-[[:Category:Programming Paradigms|paradigm]] language. Besides conventional [[procedural programming]] and object-oriented programming, it also supports [[generic programming]]. If you can't find an implementation for your task in the C++ category below, please look in the [[C]] category, as many of the tasks can be implemented identically in C and C++. diff --git a/Lang/C++/B-zier-curves-Intersections b/Lang/C++/B-zier-curves-Intersections new file mode 120000 index 0000000000..8499695feb --- /dev/null +++ b/Lang/C++/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/C++ \ No newline at end of file diff --git a/Lang/C++/Deconvolution-1D b/Lang/C++/Deconvolution-1D new file mode 120000 index 0000000000..e1264f9bbd --- /dev/null +++ b/Lang/C++/Deconvolution-1D @@ -0,0 +1 @@ +../../Task/Deconvolution-1D/C++ \ No newline at end of file diff --git a/Lang/C++/Demings-funnel b/Lang/C++/Demings-funnel new file mode 120000 index 0000000000..4aaac74cc8 --- /dev/null +++ b/Lang/C++/Demings-funnel @@ -0,0 +1 @@ +../../Task/Demings-funnel/C++ \ No newline at end of file diff --git a/Lang/C++/Determine-sentence-type b/Lang/C++/Determine-sentence-type new file mode 120000 index 0000000000..707f2f3f78 --- /dev/null +++ b/Lang/C++/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/C++ \ No newline at end of file diff --git a/Lang/C++/Distance-and-Bearing b/Lang/C++/Distance-and-Bearing new file mode 120000 index 0000000000..3df222c9d2 --- /dev/null +++ b/Lang/C++/Distance-and-Bearing @@ -0,0 +1 @@ +../../Task/Distance-and-Bearing/C++ \ No newline at end of file diff --git a/Lang/C++/EKG-sequence-convergence b/Lang/C++/EKG-sequence-convergence new file mode 120000 index 0000000000..752c0b16e1 --- /dev/null +++ b/Lang/C++/EKG-sequence-convergence @@ -0,0 +1 @@ +../../Task/EKG-sequence-convergence/C++ \ No newline at end of file diff --git a/Lang/C++/Pisano-period b/Lang/C++/Pisano-period new file mode 120000 index 0000000000..649197ce20 --- /dev/null +++ b/Lang/C++/Pisano-period @@ -0,0 +1 @@ +../../Task/Pisano-period/C++ \ No newline at end of file diff --git a/Lang/C/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/C/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..ddb6ce6303 --- /dev/null +++ b/Lang/C/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C \ No newline at end of file diff --git a/Lang/Craft-Basic/Harmonic-series b/Lang/Craft-Basic/Harmonic-series new file mode 120000 index 0000000000..a11d3963eb --- /dev/null +++ b/Lang/Craft-Basic/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Craft-Basic \ No newline at end of file diff --git a/Lang/Craft-Basic/Largest-proper-divisor-of-n b/Lang/Craft-Basic/Largest-proper-divisor-of-n new file mode 120000 index 0000000000..1f5596ae43 --- /dev/null +++ b/Lang/Craft-Basic/Largest-proper-divisor-of-n @@ -0,0 +1 @@ +../../Task/Largest-proper-divisor-of-n/Craft-Basic \ No newline at end of file diff --git a/Lang/EMal/Comments b/Lang/EMal/Comments new file mode 120000 index 0000000000..09f782bacf --- /dev/null +++ b/Lang/EMal/Comments @@ -0,0 +1 @@ +../../Task/Comments/EMal \ No newline at end of file diff --git a/Lang/EMal/Enumerations b/Lang/EMal/Enumerations new file mode 120000 index 0000000000..711fc51114 --- /dev/null +++ b/Lang/EMal/Enumerations @@ -0,0 +1 @@ +../../Task/Enumerations/EMal \ No newline at end of file diff --git a/Lang/EMal/Filter b/Lang/EMal/Filter new file mode 120000 index 0000000000..e496c77526 --- /dev/null +++ b/Lang/EMal/Filter @@ -0,0 +1 @@ +../../Task/Filter/EMal \ No newline at end of file diff --git a/Lang/EMal/Hash-from-two-arrays b/Lang/EMal/Hash-from-two-arrays new file mode 120000 index 0000000000..25f9a9c7af --- /dev/null +++ b/Lang/EMal/Hash-from-two-arrays @@ -0,0 +1 @@ +../../Task/Hash-from-two-arrays/EMal \ No newline at end of file diff --git a/Lang/EMal/Inheritance-Single b/Lang/EMal/Inheritance-Single new file mode 120000 index 0000000000..a68d11ae59 --- /dev/null +++ b/Lang/EMal/Inheritance-Single @@ -0,0 +1 @@ +../../Task/Inheritance-Single/EMal \ No newline at end of file diff --git a/Lang/EMal/String-prepend b/Lang/EMal/String-prepend new file mode 120000 index 0000000000..9ace108cf5 --- /dev/null +++ b/Lang/EMal/String-prepend @@ -0,0 +1 @@ +../../Task/String-prepend/EMal \ No newline at end of file diff --git a/Lang/F-Sharp/Minkowski-question-mark-function b/Lang/F-Sharp/Minkowski-question-mark-function new file mode 120000 index 0000000000..7a9886265b --- /dev/null +++ b/Lang/F-Sharp/Minkowski-question-mark-function @@ -0,0 +1 @@ +../../Task/Minkowski-question-mark-function/F-Sharp \ No newline at end of file diff --git a/Lang/Free-Pascal-Lazarus/Abundant-deficient-and-perfect-number-classifications b/Lang/Free-Pascal-Lazarus/Abundant-deficient-and-perfect-number-classifications new file mode 120000 index 0000000000..861558930b --- /dev/null +++ b/Lang/Free-Pascal-Lazarus/Abundant-deficient-and-perfect-number-classifications @@ -0,0 +1 @@ +../../Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus \ No newline at end of file diff --git a/Lang/FreeBASIC/Canonicalize-CIDR b/Lang/FreeBASIC/Canonicalize-CIDR new file mode 120000 index 0000000000..23d4ee9b09 --- /dev/null +++ b/Lang/FreeBASIC/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/FreeBASIC \ No newline at end of file diff --git a/Lang/FreeBASIC/Nautical-bell b/Lang/FreeBASIC/Nautical-bell new file mode 120000 index 0000000000..e2ac406a86 --- /dev/null +++ b/Lang/FreeBASIC/Nautical-bell @@ -0,0 +1 @@ +../../Task/Nautical-bell/FreeBASIC \ No newline at end of file diff --git a/Lang/J/Sum-and-product-puzzle b/Lang/J/Sum-and-product-puzzle new file mode 120000 index 0000000000..6f416bebd6 --- /dev/null +++ b/Lang/J/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/J \ No newline at end of file diff --git a/Lang/Java/15-puzzle-solver b/Lang/Java/15-puzzle-solver new file mode 120000 index 0000000000..9d7820e546 --- /dev/null +++ b/Lang/Java/15-puzzle-solver @@ -0,0 +1 @@ +../../Task/15-puzzle-solver/Java \ No newline at end of file diff --git a/Lang/Java/B-zier-curves-Intersections b/Lang/Java/B-zier-curves-Intersections new file mode 120000 index 0000000000..043cd63f13 --- /dev/null +++ b/Lang/Java/B-zier-curves-Intersections @@ -0,0 +1 @@ +../../Task/B-zier-curves-Intersections/Java \ No newline at end of file diff --git a/Lang/Java/Color-quantization b/Lang/Java/Color-quantization new file mode 120000 index 0000000000..4d565a6cb5 --- /dev/null +++ b/Lang/Java/Color-quantization @@ -0,0 +1 @@ +../../Task/Color-quantization/Java \ No newline at end of file diff --git a/Lang/Java/Compile-time-calculation b/Lang/Java/Compile-time-calculation new file mode 120000 index 0000000000..a789f870ef --- /dev/null +++ b/Lang/Java/Compile-time-calculation @@ -0,0 +1 @@ +../../Task/Compile-time-calculation/Java \ No newline at end of file diff --git a/Lang/Java/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/Java/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..0258b227f0 --- /dev/null +++ b/Lang/Java/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java \ No newline at end of file diff --git a/Lang/Java/Consecutive-primes-with-ascending-or-descending-differences b/Lang/Java/Consecutive-primes-with-ascending-or-descending-differences new file mode 120000 index 0000000000..7e16795d72 --- /dev/null +++ b/Lang/Java/Consecutive-primes-with-ascending-or-descending-differences @@ -0,0 +1 @@ +../../Task/Consecutive-primes-with-ascending-or-descending-differences/Java \ No newline at end of file diff --git a/Lang/Java/Curzon-numbers b/Lang/Java/Curzon-numbers new file mode 120000 index 0000000000..33d4de844a --- /dev/null +++ b/Lang/Java/Curzon-numbers @@ -0,0 +1 @@ +../../Task/Curzon-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Deceptive-numbers b/Lang/Java/Deceptive-numbers new file mode 120000 index 0000000000..db81eb6836 --- /dev/null +++ b/Lang/Java/Deceptive-numbers @@ -0,0 +1 @@ +../../Task/Deceptive-numbers/Java \ No newline at end of file diff --git a/Lang/Java/Descending-primes b/Lang/Java/Descending-primes new file mode 120000 index 0000000000..984d9a675b --- /dev/null +++ b/Lang/Java/Descending-primes @@ -0,0 +1 @@ +../../Task/Descending-primes/Java \ No newline at end of file diff --git a/Lang/Java/Determine-sentence-type b/Lang/Java/Determine-sentence-type new file mode 120000 index 0000000000..29a6c60854 --- /dev/null +++ b/Lang/Java/Determine-sentence-type @@ -0,0 +1 @@ +../../Task/Determine-sentence-type/Java \ No newline at end of file diff --git a/Lang/Java/Duffinian-numbers b/Lang/Java/Duffinian-numbers new file mode 120000 index 0000000000..bd207e2a7c --- /dev/null +++ b/Lang/Java/Duffinian-numbers @@ -0,0 +1 @@ +../../Task/Duffinian-numbers/Java \ No newline at end of file diff --git a/Lang/Jq/Old-Russian-measure-of-length b/Lang/Jq/Old-Russian-measure-of-length new file mode 120000 index 0000000000..b608da8973 --- /dev/null +++ b/Lang/Jq/Old-Russian-measure-of-length @@ -0,0 +1 @@ +../../Task/Old-Russian-measure-of-length/Jq \ No newline at end of file diff --git a/Lang/Lua/00-LANG.txt b/Lang/Lua/00-LANG.txt index 2494cc1b9f..e66f86629d 100644 --- a/Lang/Lua/00-LANG.txt +++ b/Lang/Lua/00-LANG.txt @@ -21,358 +21,4 @@ As a result, the base language is light—in fact, the full reference interprete * [[wp:Lua_%28programming_language%29|Wikipedia:Lua (programming language)]] ==Unimplemented programming tasks== -Output from [[Find_unimplemented_tasks]] : - -Lua has 355 unimplemented programming tasks: - 15 puzzle solver - 2048 - 4-rings or 4-squares puzzle - 9 billion names of God the integer - AKS test for primes - Abbreviations, automatic - Abbreviations, easy - Abbreviations, simple - Active Directory/Connect - Active Directory/Search for a user - Active object - Address of a variable - Aliquot sequence classifications - Anagrams/Deranged anagrams - Animation - Append a record to the end of a text file - Apply a digital filter (direct form II transposed) - Arbitrary-precision integers (included) - Archimedean spiral - Arena storage pool - Arithmetic-geometric mean/Calculate Pi - Atomic updates - Average loop length - Balanced ternary - Best shuffle - Bitcoin/address validation - Bitcoin/public point to address - Bitmap/Bresenham's line algorithm - Bitmap/Bézier curves/Cubic - Bitmap/Bézier curves/Quadratic - Bitmap/Flood fill - Bitmap/Midpoint circle algorithm - Bitmap/PPM conversion through a pipe - Bitmap/Read an image through a pipe - Bitwise IO - Brace expansion - Break OO privacy - Bulls and cows/Player - Call a function in a shared library - Canny edge detector - Carmichael 3 strong pseudoprimes - Casting out nines - Catmull–Clark subdivision surface - Chat server - Check Machin-like formulas - Checkpoint synchronization - Chinese zodiac - Cholesky decomposition - Church Numerals - Circles of given radius through two points - Closest-pair problem - Color of a screen pixel - Color quantization - Colour bars/Display - Colour pinstripe/Display - Colour pinstripe/Printer - Combinations and permutations - Commatizing numbers - Compare sorting algorithms' performance - Compile-time calculation - Compiler/AST interpreter - Compiler/code generator - Compiler/lexical analyzer - Compiler/syntax analyzer - Compiler/virtual machine interpreter - Conjugate transpose - Constrained genericity - Constrained random points on a circle - Continued fraction - Continued fraction/Arithmetic/Construct from rational number - Convert decimal number to rational - Create a file on magnetic tape - Create an object at a given address - Currency - Cut a rectangle - Death Star - Deconvolution/2D+ - Define a primitive data type - Delegates - Determine if only one instance is running - Digital root/Multiplicative digital root - Dining philosophers - Discordian date - Distributed programming - Documentation - Doubly-linked list/Definition - Doubly-linked list/Element definition - Doubly-linked list/Element insertion - Doubly-linked list/Traversal - Draw a cuboid - Draw a pixel - Draw a rotating cube - Dutch national flag problem - EKG sequence convergence - Eertree - Egyptian division - Egyptian fractions - Element-wise operations - Elementary cellular automaton - Enforced immutability - Equilibrium index - Euler's identity - Events - Extend your language - Extensible prime generator - FTP - Factors of a Mersenne number - Find common directory path - Find largest left truncatable prime in a given base - Find palindromic numbers in both binary and ternary bases - Floyd-Warshall algorithm - Four is magic - Four is the number of letters in the ... - Fractran - Function frequency - GUI component interaction - GUI enabling/disabling of controls - GUI/Maximum window dimensions - Galton box animation - Gaussian elimination - Generate random chess position - Go Fish - Greyscale bars/Display - HTTPS/Client-authenticated - Handle a signal - Hash join - Hello world/Line printer - Hello world/Web server - Hickerson series of almost integers - History variables - Hofstadter Figure-Figure sequences - Hofstadter Q sequence - Honeycombs - Horizontal sundial calculations - Host introspection - Hough transform - Hunt The Wumpus - Image convolution - Image noise - Index finite lists of positive integers - Inheritance/Single - Integer overflow - Inverted index - Inverted syntax - Jaro distance - Jewels and Stones - Joystick position - Julia set - K-d tree - K-means++ clustering - Keyboard input/Flush the keyboard buffer - Keyboard input/Keypress check - Keyboard input/Obtain a Y or N response - Keyboard macros - Knapsack problem/0-1 - Knapsack problem/Bounded - Knapsack problem/Continuous - Knuth's algorithm S - Knuth's power tree - Kolakoski sequence - LU decomposition - Largest number divisible by its digits - Last letter-first letter - Law of cosines - triples - Long multiplication - Long primes - Loops/Increment loop index within loop body - Loops/Wrong ranges - Lucas-Lehmer test - Lucky and even lucky numbers - Lychrel numbers - MD5/Implementation - Machine code - Mad Libs - Main step of GOST 28147-89 - Maze solving - Median filter - Memory allocation - Memory layout of a data structure - Metered concurrency - Metronome - Miller–Rabin primality test - Mind boggling card trick - Minesweeper game - Modular exponentiation - Modular inverse - Mouse position - Multiple regression - Multiplicative order - Narcissist - Natural sorting - Nautical bell - Negative base numbers - Nested templated data - Non-continuous subsequences - Nonogram solver - Numeric error propagation - OLE Automation - Object serialization - Odd word problem - OpenWebNet Password - Paraffins - Parallel Brute Force - Parallel calculations - Parametric polymorphism - Parametrized SQL statement - Parse an IP Address - Parsing/RPN to infix conversion - Parsing/Shunting-yard algorithm - Partition an integer X into N primes - Pascal's triangle/Puzzle - Pathological floating point problems - Pattern matching - Pentagram - Percentage difference between images - Percolation/Bond percolation - Percolation/Mean cluster density - Percolation/Mean run density - Percolation/Site percolation - Permutation test - Permutations/Rank of a permutation - Pig the dice game/Player - Pinstripe/Printer - Play recorded sounds - Plot coordinate pairs - Polymorphic copy - Polynomial long division - Polynomial regression - Pragmatic directives - Primes - allocate descendants to their ancestors - Primorial numbers - Problem of Apollonius - Pythagoras tree - Pythagorean quadruples - Pythagorean triples - QR decomposition - RCRPG - RPG Attributes Generator - RSA code - Ramer-Douglas-Peucker line simplification - Random number generator (device) - Ranking methods - Rate counter - Ray-casting algorithm - Recaman's sequence - Record sound - Reflection/Get source - Reflection/List methods - Reflection/List properties - Rendezvous - Rep-string - Resistor mesh - Retrieve and search chat history - Rosetta Code/Count examples - Rosetta Code/Find bare lang tags - Rosetta Code/Rank languages by popularity - Runge-Kutta method - S-Expressions - SEDOLs - SOAP - SQL-based authentication - Safe addition - Sailors, coconuts and a monkey problem - Same Fringe - Scope modifiers - Scope/Function names and labels - Sequence of primorial primes - Set consolidation - Set of real numbers - Set puzzle - Shortest common supersequence - Sierpinski carpet - Sierpinski pentagon - Sierpinski triangle - Simple database - Simulate input/Keyboard - Simulate input/Mouse - Singleton - Singly-linked list/Element definition - Singly-linked list/Element insertion - Singly-linked list/Traversal - Sokoban - Solve a Hidato puzzle - Solve a Hopido puzzle - Solve a Numbrix puzzle - Solve the no connection puzzle - Sorting algorithms/Heapsort - Sorting algorithms/Radix sort - Sorting algorithms/Strand sort - Sparkline in unicode - Speech synthesis - Spelling of ordinal numbers - Spinning rod animation/Text - Square but not cube - Start from a main routine - State name puzzle - Stream Merge - Subtractive generator - Sum and Product Puzzle - Sum to 100 - Superellipse - Superpermutation minimisation - Taxicab numbers - Terminal control/Coloured text - Terminal control/Cursor movement - Terminal control/Cursor positioning - Terminal control/Dimensions - Terminal control/Hiding the cursor - Terminal control/Inverse video - Terminal control/Positional read - Terminal control/Preserve screen - Terminal control/Unicode output - Ternary logic - The ISAAC Cipher - The Name Game - Thiele's interpolation formula - Topic variable - Topological sort - Total circles area - Tree traversal - Truth table - Twelve statements - URL parser - Ulam spiral (for primes) - Unicode strings - Update a configuration file - Use another language to call a function - User input/Graphical - Vampire number - Variable size/Get - Variable size/Set - Variable-length quantity - Verify distribution uniformity/Chi-squared test - Verify distribution uniformity/Naive - Video display modes - Vigenère cipher/Cryptanalysis - Visualize a tree - Vogel's approximation method - Walk a directory/Recursively - Water collected between towers - Window creation/X11 - Window management - Word search - World Cup group stage - Write to Windows event log - Xiaolin Wu's line algorithm - Yahoo! search interface - Yin and yang - Zebra puzzle - Zeckendorf arithmetic - -See also [[Reports:Tasks_not_implemented_in_Lua]] \ No newline at end of file +[[Tasks not implemented in Lua]] \ No newline at end of file diff --git a/Lang/Lua/Factorial-primes b/Lang/Lua/Factorial-primes new file mode 120000 index 0000000000..0fa5987208 --- /dev/null +++ b/Lang/Lua/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Lua \ No newline at end of file diff --git a/Lang/Lua/Particle-fountain b/Lang/Lua/Particle-fountain new file mode 120000 index 0000000000..5cdfe5c932 --- /dev/null +++ b/Lang/Lua/Particle-fountain @@ -0,0 +1 @@ +../../Task/Particle-fountain/Lua \ No newline at end of file diff --git a/Lang/M2000-Interpreter/Last-Friday-of-each-month b/Lang/M2000-Interpreter/Last-Friday-of-each-month new file mode 120000 index 0000000000..9d663b1c7c --- /dev/null +++ b/Lang/M2000-Interpreter/Last-Friday-of-each-month @@ -0,0 +1 @@ +../../Task/Last-Friday-of-each-month/M2000-Interpreter \ No newline at end of file diff --git a/Lang/Maxima/Attractive-numbers b/Lang/Maxima/Attractive-numbers new file mode 120000 index 0000000000..9cd40ac3af --- /dev/null +++ b/Lang/Maxima/Attractive-numbers @@ -0,0 +1 @@ +../../Task/Attractive-numbers/Maxima \ No newline at end of file diff --git a/Lang/MiniScript/Anti-primes b/Lang/MiniScript/Anti-primes new file mode 120000 index 0000000000..f139044edd --- /dev/null +++ b/Lang/MiniScript/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/MiniScript \ No newline at end of file diff --git a/Lang/Modula-2/Trabb-Pardo-Knuth-algorithm b/Lang/Modula-2/Trabb-Pardo-Knuth-algorithm new file mode 120000 index 0000000000..b03be3b61b --- /dev/null +++ b/Lang/Modula-2/Trabb-Pardo-Knuth-algorithm @@ -0,0 +1 @@ +../../Task/Trabb-Pardo-Knuth-algorithm/Modula-2 \ No newline at end of file diff --git a/Lang/Odin/Anti-primes b/Lang/Odin/Anti-primes new file mode 120000 index 0000000000..2e9879ece6 --- /dev/null +++ b/Lang/Odin/Anti-primes @@ -0,0 +1 @@ +../../Task/Anti-primes/Odin \ No newline at end of file diff --git a/Lang/Odin/Fibonacci-sequence b/Lang/Odin/Fibonacci-sequence new file mode 120000 index 0000000000..63383c8c82 --- /dev/null +++ b/Lang/Odin/Fibonacci-sequence @@ -0,0 +1 @@ +../../Task/Fibonacci-sequence/Odin \ No newline at end of file diff --git a/Lang/Odin/Pseudo-random-numbers-Splitmix64 b/Lang/Odin/Pseudo-random-numbers-Splitmix64 new file mode 120000 index 0000000000..57eaaa3079 --- /dev/null +++ b/Lang/Odin/Pseudo-random-numbers-Splitmix64 @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Splitmix64/Odin \ No newline at end of file diff --git a/Lang/PL-M/FASTA-format b/Lang/PL-M/FASTA-format new file mode 120000 index 0000000000..a0f59017a2 --- /dev/null +++ b/Lang/PL-M/FASTA-format @@ -0,0 +1 @@ +../../Task/FASTA-format/PL-M \ No newline at end of file diff --git a/Lang/Palo-Alto-Tiny-BASIC/00-LANG.txt b/Lang/Palo-Alto-Tiny-BASIC/00-LANG.txt index 545aaf2990..c92d6147dd 100644 --- a/Lang/Palo-Alto-Tiny-BASIC/00-LANG.txt +++ b/Lang/Palo-Alto-Tiny-BASIC/00-LANG.txt @@ -15,6 +15,18 @@ Palo Alto Tiny BASIC has some features that distinguish it from other Tiny BASIC * Lack of THEN in an IF command. * Numeric results of compare operations: 1 (if true), 0 (if false). Thus, one can use them in arithmetic expression. Note: LET A=B=0 means "set A to the result of comparing B with 0". * A prompt in an INPUT command. If the prompt is omitted, the default is a name of the variable. E.g. INPUT "WHAT IS THE HEIGHT"H will print WHAT IS THE HEIGHT: and wait to read an expression from the input device.INPUT H will print H: and so on. +* The function RND(X) that returns a random number between 1 and X (inclusive). +* Separating print items with , (comma). +* Setting widths of numeric print items. A number preceeded by # sets the width (6 by default) of following numeric print items. It does not count leading spaces. For example, + +10 PRINT "X",#2,1,10,"X" +20 PRINT 1,#4,10,20,#2,30,40 + +displays +
+X  1 10X
+      1   10   20 30 40
+
==Implementations== Palo Alto Tiny BASIC was adapted for many implementations: diff --git a/Lang/Pascal/Abundant-deficient-and-perfect-number-classifications b/Lang/Pascal/Abundant-deficient-and-perfect-number-classifications deleted file mode 120000 index ebe91e232f..0000000000 --- a/Lang/Pascal/Abundant-deficient-and-perfect-number-classifications +++ /dev/null @@ -1 +0,0 @@ -../../Task/Abundant-deficient-and-perfect-number-classifications/Pascal \ No newline at end of file diff --git a/Lang/QBasic/Canonicalize-CIDR b/Lang/QBasic/Canonicalize-CIDR new file mode 120000 index 0000000000..ec487a7a62 --- /dev/null +++ b/Lang/QBasic/Canonicalize-CIDR @@ -0,0 +1 @@ +../../Task/Canonicalize-CIDR/QBasic \ No newline at end of file diff --git a/Lang/Rust/Arithmetic-derivative b/Lang/Rust/Arithmetic-derivative new file mode 120000 index 0000000000..9089e5de0a --- /dev/null +++ b/Lang/Rust/Arithmetic-derivative @@ -0,0 +1 @@ +../../Task/Arithmetic-derivative/Rust \ No newline at end of file diff --git a/Lang/Rust/Cistercian-numerals b/Lang/Rust/Cistercian-numerals new file mode 120000 index 0000000000..7275757e17 --- /dev/null +++ b/Lang/Rust/Cistercian-numerals @@ -0,0 +1 @@ +../../Task/Cistercian-numerals/Rust \ No newline at end of file diff --git a/Lang/Rust/Colorful-numbers b/Lang/Rust/Colorful-numbers new file mode 120000 index 0000000000..3a3eebd835 --- /dev/null +++ b/Lang/Rust/Colorful-numbers @@ -0,0 +1 @@ +../../Task/Colorful-numbers/Rust \ No newline at end of file diff --git a/Lang/Rust/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k b/Lang/Rust/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k new file mode 120000 index 0000000000..32e7726ee7 --- /dev/null +++ b/Lang/Rust/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k @@ -0,0 +1 @@ +../../Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust \ No newline at end of file diff --git a/Lang/Rust/Dinesmans-multiple-dwelling-problem b/Lang/Rust/Dinesmans-multiple-dwelling-problem new file mode 120000 index 0000000000..5202c4e91b --- /dev/null +++ b/Lang/Rust/Dinesmans-multiple-dwelling-problem @@ -0,0 +1 @@ +../../Task/Dinesmans-multiple-dwelling-problem/Rust \ No newline at end of file diff --git a/Lang/Rust/Modified-random-distribution b/Lang/Rust/Modified-random-distribution new file mode 120000 index 0000000000..af3045024d --- /dev/null +++ b/Lang/Rust/Modified-random-distribution @@ -0,0 +1 @@ +../../Task/Modified-random-distribution/Rust \ No newline at end of file diff --git a/Lang/Rust/Sum-and-product-puzzle b/Lang/Rust/Sum-and-product-puzzle new file mode 120000 index 0000000000..c841eb9b4e --- /dev/null +++ b/Lang/Rust/Sum-and-product-puzzle @@ -0,0 +1 @@ +../../Task/Sum-and-product-puzzle/Rust \ No newline at end of file diff --git a/Lang/S-BASIC/Array-length b/Lang/S-BASIC/Array-length new file mode 120000 index 0000000000..376b70f748 --- /dev/null +++ b/Lang/S-BASIC/Array-length @@ -0,0 +1 @@ +../../Task/Array-length/S-BASIC \ No newline at end of file diff --git a/Lang/Sidef/00-LANG.txt b/Lang/Sidef/00-LANG.txt index f44393181c..a63ddf8a52 100644 --- a/Lang/Sidef/00-LANG.txt +++ b/Lang/Sidef/00-LANG.txt @@ -25,4 +25,8 @@ The language is mostly used as a research programming language. For more details, see: * Gitbook: [https://trizen.gitbook.io/sidef-lang/ https://trizen.gitbook.io/sidef-lang/] * Tutorial: [https://notabug.org/trizen/sidef/wiki https://notabug.org/trizen/sidef/wiki] -* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef] \ No newline at end of file +* Development page: [https://github.com/trizen/sidef https://github.com/trizen/sidef] + +==Todo== + +[[Tasks_not_implemented_in_Sidef]] \ No newline at end of file diff --git a/Lang/Sidef/Factorial-primes b/Lang/Sidef/Factorial-primes new file mode 120000 index 0000000000..653de65402 --- /dev/null +++ b/Lang/Sidef/Factorial-primes @@ -0,0 +1 @@ +../../Task/Factorial-primes/Sidef \ No newline at end of file diff --git a/Lang/Tcl/Harmonic-series b/Lang/Tcl/Harmonic-series new file mode 120000 index 0000000000..f5f96a3ec9 --- /dev/null +++ b/Lang/Tcl/Harmonic-series @@ -0,0 +1 @@ +../../Task/Harmonic-series/Tcl \ No newline at end of file diff --git a/Lang/Tcl/Pseudo-random-numbers-Middle-square-method b/Lang/Tcl/Pseudo-random-numbers-Middle-square-method new file mode 120000 index 0000000000..3819fd9c41 --- /dev/null +++ b/Lang/Tcl/Pseudo-random-numbers-Middle-square-method @@ -0,0 +1 @@ +../../Task/Pseudo-random-numbers-Middle-square-method/Tcl \ No newline at end of file diff --git a/Lang/Transact-SQL/Julia-set b/Lang/Transact-SQL/Julia-set new file mode 120000 index 0000000000..6f30c72f4e --- /dev/null +++ b/Lang/Transact-SQL/Julia-set @@ -0,0 +1 @@ +../../Task/Julia-set/Transact-SQL \ No newline at end of file diff --git a/Task/15-puzzle-solver/Java/15-puzzle-solver.java b/Task/15-puzzle-solver/Java/15-puzzle-solver.java new file mode 100644 index 0000000000..c45a1de8d6 --- /dev/null +++ b/Task/15-puzzle-solver/Java/15-puzzle-solver.java @@ -0,0 +1,143 @@ +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.stream.Collectors; + +public final class Puzzle15Solver { + + public static void main(String[] aArgs) { + List start = List.of( 15, 14, 1, 6, 9, 11, 4, 12, 0, 10, 7, 3, 13, 8, 5, 2 ); + final int zeroIndex = 8; + Puzzle initial = new Puzzle(start, new ArrayList(), zeroIndex, 0); + openSet.add(initial); + System.out.println("Solving the 15 puzzle:"); + initial.display(); + + while ( solution == null ) { + search(); + } + + System.out.println(solution.moves.stream().collect(Collectors.joining(""))); + System.out.println("Number of steps: " + solution.moves.size()); + System.out.println("Number of puzzle states checked: " + closedSet.size()); + } + + private static void search() { + Puzzle current = openSet.poll(); + closedSet.add(current); + final int zeroIndex = current.zeroIndex; + final int row = zeroIndex / 4; + final int column = zeroIndex % 4; + + if ( column > 0 ) { + Puzzle nextPuzzle = current.clone(); + nextPuzzle.makeMove(Move.LEFT); + } + if ( column < 3 ) { + Puzzle nextPuzzle = current.clone(); + nextPuzzle.makeMove(Move.RIGHT); + } + if ( row > 0 ) { + Puzzle nextPuzzle = current.clone(); + nextPuzzle.makeMove(Move.UP); + } + if ( row < 3 ) { + Puzzle nextPuzzle = current.clone(); + nextPuzzle.makeMove(Move.DOWN); + } + } + + private enum Move { + LEFT("L", -1), RIGHT("R", +1), UP("U", -4), DOWN("D", +4); + + private Move(String aSymbol, int aStep) { + symbol = aSymbol; + step = aStep; + } + + private String symbol; + private Integer step; + } + + private static class Puzzle { + + public Puzzle(List aTiles, List aMoves, int aZeroIndex, int aSearchDepth) { + tiles = aTiles; + moves = aMoves; + zeroIndex = aZeroIndex; + searchDepth = aSearchDepth; + } + + public void makeMove(Move aMove) { + Integer temp = tiles.get(zeroIndex + aMove.step); + tiles.set(zeroIndex + aMove.step, 0); + tiles.set(zeroIndex, temp); + + zeroIndex += aMove.step; + moves.add(aMove.symbol); + + if ( ! closedSet.contains(this) ) { + openSet.add(this); + if ( tiles.equals(Puzzle.GOAL) ) { + solution = this; + } + } + } + + public long heuristic() { + int distance = 0; + for ( int i = 0; i < tiles.size(); i++ ) { + final int tile = tiles.get(i); + if ( tile > 0 ) { + distance += Math.abs( ( i / 4 ) - ( tile - 1 ) / 4 ) + Math.abs( ( i % 4 ) - ( tile - 1 ) % 4 ); + } + } + return distance + searchDepth; + } + + public Puzzle clone() { + return new Puzzle(new ArrayList(tiles), new ArrayList(moves), zeroIndex, searchDepth + 1); + } + + public void display() { + for ( int i = 0; i < tiles.size(); i++ ) { + System.out.print(String.format("%s%2d%s", + ( i % 4 == 0 ) ? "[" : "", tiles.get(i), ( i % 4 == 3 ) ? "]\n" : " ")); + } + System.out.println(); + } + + @Override + public boolean equals(Object aObject) { + return switch(aObject) { + case Puzzle puzzle -> tiles.equals(puzzle.tiles); + case Object object -> false; + }; + } + + @Override + public int hashCode() { + int hash = 3; + hash = 23 * hash + tiles.hashCode(); + hash = 23 * hash + zeroIndex; + return hash; + } + + private List tiles; + private List moves; + private int zeroIndex; + private int searchDepth; + + private static final List GOAL = List.of( 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0 ); + + } + + private static Queue openSet = + new PriorityQueue( (one, two) -> Long.compare(one.heuristic(), two.heuristic()) ); + private static Set closedSet = new HashSet(); + private static Puzzle solution; + +} diff --git a/Task/24-game/Elena/24-game.elena b/Task/24-game/Elena/24-game.elena index ef481696de..fc6d5d8743 100644 --- a/Task/24-game/Elena/24-game.elena +++ b/Task/24-game/Elena/24-game.elena @@ -7,7 +7,7 @@ import extensions; class ExpressionTree { - object theTree; + object _tree; constructor(s) { @@ -18,40 +18,40 @@ class ExpressionTree var node := new DynamicStruct(); ch => - $43 { node.Level := level + 1; node.Operation := __subj add } // + - $45 { node.Level := level + 1; node.Operation := __subj subtract } // - - $42 { node.Level := level + 2; node.Operation := __subj multiply } // * - $47 { node.Level := level + 2; node.Operation := __subj divide } // / - $40 { level.append(10); ^ self } // ( - $41 { level.reduce(10); ^ self } // ) + $43 { node.Level := level + 1; node.Operation := mssg add } // + + $45 { node.Level := level + 1; node.Operation := mssg subtract } // - + $42 { node.Level := level + 2; node.Operation := mssg multiply } // * + $47 { node.Level := level + 2; node.Operation := mssg divide } // / + $40 { level.append(10); ^ self } // ( + $41 { level.reduce(10); ^ self } // ) : { node.Leaf := ch.toString().toReal(); node.Level := level + 3 }; - if (nil == theTree) + if (nil == _tree) { - theTree := node + _tree := node } else { - if (theTree.Level >= node.Level) + if (_tree.Level >= node.Level) { - node.Left := theTree; - node.Right := nilValue; + node.Left := _tree; + node.Right := nil; - theTree := node + _tree := node } else { - var top := theTree; - while ((nilValue != top.Right)&&(top.Right.Level < node.Level)) - { top := top.Right }; + var top := _tree; + while ((nil != top.Right)&&(top.Right.Level < node.Level)) + { top := top.Right }; - node.Left := top.Right; - node.Right := nilValue; + node.Left := top.Right; + node.Right := nil; - top.Right := node + top.Right := node } } } @@ -59,7 +59,7 @@ class ExpressionTree eval(node) { - if (node.containsProperty(subjconst Leaf)) + if (node.containsProperty(mssg Leaf)) { ^ node.Leaf } @@ -75,14 +75,14 @@ class ExpressionTree } get Value() - <= eval(theTree); + <= eval(_tree); readLeaves(list, node) { if (nil == node) { InvalidArgumentException.raise() }; - if (node.containsProperty(subjconst Leaf)) + if (node.containsProperty(mssg Leaf)) { list.append(node.Leaf) } @@ -94,7 +94,7 @@ class ExpressionTree } readLeaves(list) - <= readLeaves(list,theTree); + <= readLeaves(list,_tree); } // --- Game --- @@ -112,10 +112,10 @@ class TwentyFourGame { theNumbers := new object[] { - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9, - 1 + randomGenerator.eval:9 + 1 + randomGenerator.nextInt:9, + 1 + randomGenerator.nextInt:9, + 1 + randomGenerator.nextInt:9, + 1 + randomGenerator.nextInt:9 } } @@ -149,8 +149,11 @@ class TwentyFourGame var leaves := new ArrayList(); tree.readLeaves:leaves; - ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) - { console.printLine:"Invalid input. Enter an equation using all of those four digits. Try again."; ^ self }; + ifnot (leaves.ascendant().sequenceEqual(theNumbers.ascendant())) { + console + .printLine:"Invalid input. Enter an equation using all of those four digits. Try again."; + ^ self + }; var result := tree.Value; if (result == 24) @@ -188,7 +191,8 @@ extension gameOp } catch(Exception e) { - console.printLine:"An error occurred. Check your input and try again." + console.printLine:e + //console.printLine:"An error occurred. Check your input and try again." } }; @@ -197,6 +201,8 @@ extension gameOp } } +// --- program --- + public program() { var game := new TwentyFourGame().help(); diff --git a/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena b/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena index eeef1e1ab9..54a7e75cfa 100644 --- a/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena +++ b/Task/99-bottles-of-beer/Elena/99-bottles-of-beer.elena @@ -14,7 +14,7 @@ extension bottleOp { bool next() = n > 0; - get() = new StringWriter() + get Value() = new StringWriter() .printLine(n.bottleDescription()," of beer on the wall") .printLine(n.bottleDescription()," of beer") .printLine("Take one down, pass it around") @@ -22,7 +22,7 @@ extension bottleOp reset() {} - enumerable() = __target; + enumerable() = weak self; } }; } diff --git a/Task/A+B/Elena/a+b-2.elena b/Task/A+B/Elena/a+b-2.elena index 0a28b451d9..8097b76574 100644 --- a/Task/A+B/Elena/a+b-2.elena +++ b/Task/A+B/Elena/a+b-2.elena @@ -5,6 +5,6 @@ public program() { console.printLine(console.readLine() .split() - .selectBy(mssgconst toInt[1]) + .selectBy(mssgconst toInt[1]) .summarize()) } diff --git a/Task/ASCII-art-diagram-converter/AutoHotkey/ascii-art-diagram-converter.ahk b/Task/ASCII-art-diagram-converter/AutoHotkey/ascii-art-diagram-converter.ahk new file mode 100644 index 0000000000..fd95154e51 --- /dev/null +++ b/Task/ASCII-art-diagram-converter/AutoHotkey/ascii-art-diagram-converter.ahk @@ -0,0 +1,59 @@ +Header := " +(LTrim + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ID | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + |QR| Opcode |AA|TC|RD|RA| Z | RCODE | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | QDCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ANCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | NSCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ + | ARCOUNT | + +--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+--+ +)" + +Data := "78477BBF5496E12E1BF169A4" +MsgBox % result := ASCII_art_diagram_converter(Header, Data) +return + +ASCII_art_diagram_converter(Header, Data){ + oDataBin := [] + for i, h in StrSplit(Data) + for i, v in StrSplit(SubStr("0000" . ConvertBase(16, 2, h), -3)) + oDataBin.Push(v) + + bitWidth := StrLen(StrSplit(Header, "+").2) + 1 + prevW := 0 + result := "Name`t`tSize`tBinary" + for i, line in StrSplit(Header, "`n", "`r") + { + if Mod(A_Index, 2) + continue + strtPos := 0 + loop + { + if w := (strtPos := InStr(line, "|",, ++strtPos)) // bitWidth + { + b := "" + loop % width := w - prevW + b .= oDataBin.RemoveAt(1) + result .= "`n" Trim(StrSplit(line, "|")[A_Index]) "`t`t" width . "`t" b + } + prevW := w + } + until !strtPos + } + return result +} + +ConvertBase(InputBase, OutputBase, nptr){ ; Base 2 - 36 ; https://www.autohotkey.com/boards/viewtopic.php?t=3925#p21143 + static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64" + static v := A_IsUnicode ? "_i64tow" : "_i64toa" + VarSetCapacity(s, 66, 0) + value := DllCall("msvcrt.dll\" u, "Str", nptr, "UInt", 0, "UInt", InputBase, "CDECL Int64") + DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL") + return s +} diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus/abundant-deficient-and-perfect-number-classifications.pas b/Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus/abundant-deficient-and-perfect-number-classifications.pas new file mode 100644 index 0000000000..f64e203a0d --- /dev/null +++ b/Task/Abundant-deficient-and-perfect-number-classifications/Free-Pascal-Lazarus/abundant-deficient-and-perfect-number-classifications.pas @@ -0,0 +1,49 @@ +program KindOfN; //[deficient,perfect,abundant] +{$IFDEF FPC} + {$MODE DELPHI}{$OPTIMIZATION ON,ALL}{$COPERATORS ON}{$CODEALIGN proc=16} +{$ENDIF} +{$IFDEF WINDOWS} {$APPTYPE CONSOLE}{$ENDIF} +uses + sysutils,PrimeDecomp // limited to 1.2e11 +{$IFDEF WINDOWS},Windows{$ENDIF} + ; +//alternative copy and paste PrimeDecomp.inc for TIO.RUN +{$I PrimeDecomp.inc} +type + tKindIdx = 0..2;//[deficient,perfect,abundant]; + tKind = array[tKindIdx] of Uint64; + +procedure GetKind(Limit:Uint64); +var + pPrimeDecomp :tpPrimeFac; + SumOfKind : tKind; + n: NativeUInt; + c: NativeInt; + T0:Int64; +Begin + writeln('Limit: ',LIMIT); + T0 := GetTickCount64; + fillchar(SumOfKind,SizeOf(SumOfKind),#0); + n := 1; + Init_Sieve(n); + repeat + pPrimeDecomp:= GetNextPrimeDecomp; + c := pPrimeDecomp^.pfSumOfDivs-2*n; + c := ORD(c>0)-ORD(c<0)+1;//sgn(c)+1 + inc(SumOfKind[c]); + inc(n); + until n > LIMIT; + T0 := GetTickCount64-T0; + writeln('deficient: ',SumOfKind[0]); + writeln('abundant: ',SumOfKind[2]); + writeln('perfect: ',SumOfKind[1]); + writeln('runtime ',T0/1000:0:3,' s'); + writeln; +end; + +Begin + InitSmallPrimes; //using PrimeDecomp.inc + GetKind(20000); + GetKind(10*1000*1000); + GetKind(524*1000*1000); +end. diff --git a/Task/Abundant-deficient-and-perfect-number-classifications/Pascal/abundant-deficient-and-perfect-number-classifications.pas b/Task/Abundant-deficient-and-perfect-number-classifications/Pascal/abundant-deficient-and-perfect-number-classifications.pas deleted file mode 100644 index d66fb4c8c3..0000000000 --- a/Task/Abundant-deficient-and-perfect-number-classifications/Pascal/abundant-deficient-and-perfect-number-classifications.pas +++ /dev/null @@ -1,214 +0,0 @@ -program AmicablePairs; -{find amicable pairs in a limited region 2..MAX -beware that >both< numbers must be smaller than MAX -there are 455 amicable pairs up to 524*1000*1000 -correct up to -#437 460122410 -} -//optimized for freepascal 2.6.4 32-Bit -{$IFDEF FPC} - {$MODE DELPHI} - {$OPTIMIZATION ON,peephole,cse,asmcse,regvar} - {$CODEALIGN loop=1,proc=8} -{$ELSE} - {$APPTYPE CONSOLE} -{$ENDIF} - -uses - sysutils; -const - MAX = 20000; -//{$IFDEF UNIX} MAX = 524*1000*1000;{$ELSE}MAX = 499*1000*1000;{$ENDIF} -type - tValue = LongWord; - tpValue = ^tValue; - tPower = array[0..31] of tValue; - tIndex = record - idxI, - idxS : tValue; - end; - tdpa = array[0..2] of LongWord; -var - power : tPower; - PowerFac : tPower; - DivSumField : array[0..MAX] of tValue; - Indices : array[0..511] of tIndex; - DpaCnt : tdpa; - -procedure Init; -var - i : LongInt; -begin - DivSumField[0]:= 0; - For i := 1 to MAX do - DivSumField[i]:= 1; -end; - -procedure ProperDivs(n: tValue); -//Only for output, normally a factorication would do -var - su,so : string; - i,q : tValue; -begin - su:= '1'; - so:= ''; - i := 2; - while i*i <= n do - begin - q := n div i; - IF q*i -n = 0 then - begin - su:= su+','+IntToStr(i); - IF q <> i then - so:= ','+IntToStr(q)+so; - end; - inc(i); - end; - writeln(' [',su+so,']'); -end; - -procedure AmPairOutput(cnt:tValue); -var - i : tValue; - r : double; -begin - r := 1.0; - For i := 0 to cnt-1 do - with Indices[i] do - begin - writeln(i+1:4,IdxI:12,IDxS:12,' ratio ',IdxS/IDxI:10:7); - if r < IdxS/IDxI then - r := IdxS/IDxI; - IF cnt < 20 then - begin - ProperDivs(IdxI); - ProperDivs(IdxS); - end; - end; - writeln(' max ratio ',r:10:4); -end; - -function Check:tValue; -var - i,s,n : tValue; -begin - fillchar(DpaCnt,SizeOf(dpaCnt),#0); - n := 0; - For i := 1 to MAX do - begin - //s = sum of proper divs (I) == sum of divs (I) - I - s := DivSumField[i]-i; - IF (s <=MAX) AND (s>i) then - begin - IF DivSumField[s]-s = i then - begin - With indices[n] do - begin - idxI := i; - idxS := s; - end; - inc(n); - end; - end; - inc(DpaCnt[Ord(s>=i)-Ord(s<=i)+1]); - end; - result := n; -end; - -Procedure CalcPotfactor(prim:tValue); -//PowerFac[k] = (prim^(k+1)-1)/(prim-1) == Sum (i=1..k) prim^i -var - k: tValue; - Pot, //== prim^k - PFac : Int64; -begin - Pot := prim; - PFac := 1; - For k := 0 to High(PowerFac) do - begin - PFac := PFac+Pot; - IF (POT > MAX) then - BREAK; - PowerFac[k] := PFac; - Pot := Pot*prim; - end; -end; - -procedure InitPW(prim:tValue); -begin - fillchar(power,SizeOf(power),#0); - CalcPotfactor(prim); -end; - -function NextPotCnt(p: tValue):tValue;inline; -//return the first power <> 0 -//power == n to base prim -var - i : tValue; -begin - result := 0; - repeat - i := power[result]; - Inc(i); - IF i < p then - BREAK - else - begin - i := 0; - power[result] := 0; - inc(result); - end; - until false; - power[result] := i; -end; - -function Sieve(prim: tValue):tValue; -//simple version -var - actNumber : tValue; -begin - while prim <= MAX do - begin - InitPW(prim); - //actNumber = actual number = n*prim - //power == n to base prim - actNumber := prim; - while actNumber < MAX do - begin - DivSumField[actNumber] := DivSumField[actNumber] *PowerFac[NextPotCnt(prim)]; - inc(actNumber,prim); - end; - //next prime - repeat - inc(prim); - until (DivSumField[prim] = 1); - end; - result := prim; -end; - -var - T2,T1,T0: TDatetime; - APcnt: tValue; - -begin - T0:= time; - Init; - Sieve(2); - T1:= time; - APCnt := Check; - T2:= time; - - //AmPairOutput(APCnt); - writeln(Max:10,' upper limit'); - writeln(DpaCnt[0]:10,' deficient'); - writeln(DpaCnt[1]:10,' perfect'); - writeln(DpaCnt[2]:10,' abundant'); - writeln(DpaCnt[2]/Max:14:10,' ratio abundant/upper Limit '); - writeln(DpaCnt[0]/Max:14:10,' ratio abundant/upper Limit '); - writeln(DpaCnt[2]/DpaCnt[0]:14:10,' ratio abundant/deficient '); - writeln('Time to calc sum of divs ',FormatDateTime('HH:NN:SS.ZZZ' ,T1-T0)); - writeln('Time to find amicable pairs ',FormatDateTime('HH:NN:SS.ZZZ' ,T2-T1)); - {$IFNDEF UNIX} - readln; - {$ENDIF} -end. diff --git a/Task/Anti-primes/ALGOL-68/anti-primes.alg b/Task/Anti-primes/ALGOL-68/anti-primes.alg index 2de1e9255b..f84b0322e1 100644 --- a/Task/Anti-primes/ALGOL-68/anti-primes.alg +++ b/Task/Anti-primes/ALGOL-68/anti-primes.alg @@ -1,19 +1,20 @@ BEGIN # find some anti-primes: numbers with more divisors than the # # previous numbers # - INT max number := 10 000; + REF[]INT ndc := HEAP[ 1 : 0 ]INT; # table of divisor counts # INT max divisors := 0; - # construct a table of the divisor counts # - [ 1 : max number ]INT ndc; FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD; - FOR i FROM 2 TO UPB ndc DO - FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD - OD; - # show the numbers with more divisors than their predecessors # - INT a count := 0; - FOR i TO UPB ndc WHILE a count < 20 DO - INT divisor count = ndc[ i ]; - IF divisor count > max divisors THEN - print( ( " ", whole( i, 0 ) ) ); - max divisors := divisor count; + INT a count := 0; + FOR n WHILE a count < 20 DO + IF n > UPB ndc THEN + # need a bigger table of divisor counts # + ndc := HEAP[ 1 : UPB ndc + 5 000 ]INT; + FOR i FROM 1 TO UPB ndc DO ndc[ i ] := 1 OD; + FOR i FROM 2 TO UPB ndc DO + FOR j FROM i BY i TO UPB ndc DO ndc[ j ] +:= 1 OD + OD + FI; + IF ndc[ n ] > max divisors THEN + print( ( " ", whole( n, 0 ) ) ); + max divisors := ndc[ n ]; a count +:= 1 FI OD; diff --git a/Task/Anti-primes/Lua/anti-primes.lua b/Task/Anti-primes/Lua/anti-primes-1.lua similarity index 100% rename from Task/Anti-primes/Lua/anti-primes.lua rename to Task/Anti-primes/Lua/anti-primes-1.lua diff --git a/Task/Anti-primes/Lua/anti-primes-2.lua b/Task/Anti-primes/Lua/anti-primes-2.lua new file mode 100644 index 0000000000..a849a48fa0 --- /dev/null +++ b/Task/Anti-primes/Lua/anti-primes-2.lua @@ -0,0 +1,29 @@ +-- Find the first 20 antiprimes. + +-- returns a table of the first goal antiprimes +function antiprimes(goal) + local maxNumber = 0 + local ndc = {} -- table of divisor counts - initially empty + local list, number, mostFactors = {}, 1, 0 + while #list < goal do + if number > #ndc then + -- need a bigger table of divisor counts + maxNumber = maxNumber + 5000 + ndc = {} + for i = 1, maxNumber do ndc[ i ] = 1 end + for i = 2, maxNumber do + for j = i, maxNumber, i do ndc[ j ] = ndc[ j ] + 1 end + end + end + local factors = ndc[ number ] + if factors > mostFactors then + table.insert( list, number ) + mostFactors = factors + end + number = number + 1 + end + return list +end + +-- display the antiprimes +oo.write( table.concat( antiprimes( 20 ), " " ) ) diff --git a/Task/Anti-primes/MiniScript/anti-primes.mini b/Task/Anti-primes/MiniScript/anti-primes.mini new file mode 100644 index 0000000000..b3e3966c36 --- /dev/null +++ b/Task/Anti-primes/MiniScript/anti-primes.mini @@ -0,0 +1,33 @@ +// Find the first 20 antiprimes. + +// returns a table of the first goal antiprimes +antiprimes = function(goal) + maxNumber = 0 + ndc = [] // table of divisor counts - initially empty + list = [0] * goal; number = 1; mostFactors = 0 + aCount = 0 + while aCount < goal + if number > maxNumber then + // need a bigger table of divisor counts + maxNumber = maxNumber + 5000 + ndc = [1] * ( maxNumber + 1 ) + ndc[ 0 ] = 0 + for i in range( 2, maxNumber ) + for j in range( i, maxNumber, i ) + ndc[ j ] = ndc[ j ] + 1 + end for + end for + end if + factors = ndc[ number ] + if factors > mostFactors then + list[ aCount ] = number + mostFactors = factors + aCount = aCount + 1 + end if + number = number + 1 + end while + return list +end function + +// display the antiprimes +print antiprimes( 20 ).join( " " ) diff --git a/Task/Anti-primes/Odin/anti-primes.odin b/Task/Anti-primes/Odin/anti-primes.odin new file mode 100644 index 0000000000..6658df8e73 --- /dev/null +++ b/Task/Anti-primes/Odin/anti-primes.odin @@ -0,0 +1,42 @@ +package antiprimes +import "core:fmt" + +main :: proc() { + AntiPrimeCount, MaxDivisors, Divisors, n: u64 + MaxAntiPrime: u64 = 20 + fmt.print("\nFirst 20 anti-primes\n") + fmt.println("--------------------") + for (AntiPrimeCount < MaxAntiPrime) { + n += 1 + Divisors = DivisorCount(n) + if Divisors > MaxDivisors { + fmt.print(n, " ") + MaxDivisors = Divisors + AntiPrimeCount += 1 + } + } +} + +DivisorCount :: proc(v: u64) -> u64 { + total: u64 = 1 + a := v + if a == 0 { + return 0 + } + for a % 2 == 0 { + total += 1 + a /= 2 + } + for p: u64 = 3; p * p <= a; p += 2 { + count: u64 = 1 + for a % p == 0 { + count += 1 + a /= p + } + total *= count + } + if a > 1 { + total *= 2 + } + return total +} diff --git a/Task/Anti-primes/Ring/anti-primes.ring b/Task/Anti-primes/Ring/anti-primes-1.ring similarity index 100% rename from Task/Anti-primes/Ring/anti-primes.ring rename to Task/Anti-primes/Ring/anti-primes-1.ring diff --git a/Task/Anti-primes/Ring/anti-primes-2.ring b/Task/Anti-primes/Ring/anti-primes-2.ring new file mode 100644 index 0000000000..1d44cbb7bf --- /dev/null +++ b/Task/Anti-primes/Ring/anti-primes-2.ring @@ -0,0 +1,36 @@ +# find the first 20 antiprimes +# - numbers woth more divisors than the previous numbers + +numberOfDivisorCounts = 0 +maxDivisor = 0 +num = 0 +n = 0 +result = list(20) +while num < 20 + n += 1 + if n > numberOfDivisorCounts + # need a bigger table of divisor counts + numberOfDivisorCounts += 5000 + ndc = list(numberOfDivisorCounts) + for i = 1 to numberOfDivisorCounts + ndc[ i ] = 1 + next + for i = 2 to numberOfDivisorCounts + j = i + while j <= numberOfDivisorCounts + ndc[ j ] = ndc[ j ] + 1 + j += i + end + next + ok + div = ndc[ n ] + if (div > maxDivisor) + maxDivisor = div + num += 1 + result[num] = n + ok +end +see result[1] +for n = 2 to len(result) + see " " + string(result[n]) +next diff --git a/Task/Anti-primes/Ruby/anti-primes.rb b/Task/Anti-primes/Ruby/anti-primes.rb index 86541cc62b..532be171a8 100644 --- a/Task/Anti-primes/Ruby/anti-primes.rb +++ b/Task/Anti-primes/Ruby/anti-primes.rb @@ -1,6 +1,6 @@ require 'prime' def num_divisors(n) - n.prime_division.inject(1){|prod, (_p,n)| prod *= (n + 1) } + n.prime_division.inject(1){|prod, (_p,n)| prod * (n + 1) } end anti_primes = Enumerator.new do |y| # y is the yielder diff --git a/Task/Arbitrary-precision-integers-included-/Sidef/arbitrary-precision-integers-included-.sidef b/Task/Arbitrary-precision-integers-included-/Sidef/arbitrary-precision-integers-included-.sidef index 1f06a61cc6..8f4c7ec041 100644 --- a/Task/Arbitrary-precision-integers-included-/Sidef/arbitrary-precision-integers-included-.sidef +++ b/Task/Arbitrary-precision-integers-included-/Sidef/arbitrary-precision-integers-included-.sidef @@ -1,3 +1,3 @@ -var x = 5**(4**(3**2)); -var y = x.to_s; -printf("5**4**3**2 = %s...%s and has %i digits\n", y.ft(0,19), y.ft(-20), y.len); +var x = 5**(4**(3**2)) +var y = x.to_s +printf("5**4**3**2 = %s...%s and has %i digits\n", y.first(20), y.last(20), y.len) diff --git a/Task/Arithmetic-derivative/Rust/arithmetic-derivative.rust b/Task/Arithmetic-derivative/Rust/arithmetic-derivative.rust new file mode 100644 index 0000000000..e81375c533 --- /dev/null +++ b/Task/Arithmetic-derivative/Rust/arithmetic-derivative.rust @@ -0,0 +1,25 @@ +use prime_factorization::Factorization; + +fn d(n: i128) -> i128 { + if n < 0 { + return -(d(-n)); + } else if n < 2 { + return 0; + } else { + let fpairs = Factorization::run(n as u128).prime_factor_repr(); + if fpairs.len() == 1 && fpairs[0].1 == 1 { + return 1; + } + return fpairs.iter().fold(0_i128, |p, q| p + n * (q.1 as i128) / (q.0 as i128)); + } +} + +fn main() { + for n in -99..101 { + print!("{:5}{}", d(n), { if n % 10 == 0 { "\n" } else {""} }); + } + println!(); + for m in 1..21 { + println!("(D for 10 ^ {}) divided by 7 is {}", m, d(10_i128.pow(m)) / 7) + } +} diff --git a/Task/Array-length/S-BASIC/array-length.basic b/Task/Array-length/S-BASIC/array-length.basic new file mode 100644 index 0000000000..3f753e3dc8 --- /dev/null +++ b/Task/Array-length/S-BASIC/array-length.basic @@ -0,0 +1,13 @@ +dim string animals(2) rem here is our array +var array_struct_address = integer +based array_size = integer + +animals(1) = "ardvark" +animals(2) = "bison" + +location spec array_struct_address = animals +base array_size at array_struct_address + 5 + +print "Size of array ="; array_size + +end diff --git a/Task/Ascending-primes/00-TASK.txt b/Task/Ascending-primes/00-TASK.txt index f84794ce53..643622eba2 100644 --- a/Task/Ascending-primes/00-TASK.txt +++ b/Task/Ascending-primes/00-TASK.txt @@ -14,5 +14,6 @@ at least one significantly better and much faster way, needing a mere 511 odd/pr ;Related: *[[Primes with digits in nondecreasing order]] (infinite series allowing duplicate digits, whereas this isn't and doesn't) *[[Pandigital prime]] (whereas this is the smallest, with gaps in the used digits being permitted) +*[[Descending primes]] diff --git a/Task/Attractive-numbers/Maxima/attractive-numbers.maxima b/Task/Attractive-numbers/Maxima/attractive-numbers.maxima new file mode 100644 index 0000000000..2f3fad1b07 --- /dev/null +++ b/Task/Attractive-numbers/Maxima/attractive-numbers.maxima @@ -0,0 +1,7 @@ +AttractiveNumber(N):=block([Q:0], + if not primep(N) then ( + if primep(apply("+", map(lambda([Z], Z[2]), ifactors(N)))) then Q: N + ), Q +)$ + +delete(0, makelist(AttractiveNumber(K), K, 1, 120)); diff --git a/Task/Averages-Median/ARM-Assembly/averages-median.arm b/Task/Averages-Median/ARM-Assembly/averages-median.arm new file mode 100644 index 0000000000..5b06da83df --- /dev/null +++ b/Task/Averages-Median/ARM-Assembly/averages-median.arm @@ -0,0 +1,493 @@ +/* ARM assembly Raspberry PI */ +/* program averageMed.s */ +/* use quickselect look pseudo code in wikipedia quickselect */ + +/************************************/ +/* Constantes */ +/************************************/ +/* for constantes see task include a file in arm assembly */ +.include "../constantes.inc" + +/*********************************/ +/* Initialized data */ +/*********************************/ +.data +szMessResultValue: .asciz "Result : " +szCarriageReturn: .asciz "\n" + +.align 4 +TableNumber: .float 4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2 +.equ NBELEMENTS, (. - TableNumber) / 4 +TableNumber2: .float 4.1, 7.2, 1.7, 9.3, 4.4, 3.2 +.equ NBELEMENTS2, (. - TableNumber2) / 4 +/*********************************/ +/* UnInitialized data */ +/*********************************/ +.bss +sZoneConv: .skip 24 +sZoneConv1: .skip 24 +/*********************************/ +/* code section */ +/*********************************/ +.text +.global main +main: @ entry of program + + ldr r0,iAdrTableNumber @ address number table + mov r1,#0 @ index first item + mov r2,#NBELEMENTS -1 @ index last item + bl searchMedian + ldr r0,iAdrTableNumber2 @ address number table 2 + mov r1,#0 @ index first item + mov r2,#NBELEMENTS2 -1 @ index last item + bl searchMedian + +100: @ standard end of the program + mov r0, #0 @ return code + mov r7, #EXIT @ request to exit program + svc #0 @ perform the system call + +iAdrszCarriageReturn: .int szCarriageReturn +iAdrTableNumber: .int TableNumber +iAdrTableNumber2: .int TableNumber2 +iAdrsZoneConv: .int sZoneConv +iAdrszMessResultValue: .int szMessResultValue +/***************************************************/ +/* search median term in float array */ +/***************************************************/ +/* r0 contains the address of table */ +/* r1 contains index of first item */ +/* r2 contains index of last item */ +searchMedian: + push {r1-r5,lr} @ save registers + mov r5,r0 @ save array address + add r4,r1,r2 + add r4,r4,#1 @ sum numbers terms + tst r4,#1 @ odd ? + bne 1f + lsr r3,r4,#1 @ compute median index + bl select @ call selection + vmov s0,r0 @ save first result + sub r3,r3,#1 @ second term + mov r0,r5 + bl select @ call selection + vmov s1,r0 @ save 2ieme résult + vadd.f32 s0,s1 @ compute average two résults + mov r0,#2 + vmov s1,r0 + vcvt.f32.u32 s1,s1 @ conversion integer -> float + vdiv.f32 s0,s0,s1 + b 2f +1: @ even + lsr r3,r4,#1 + bl select @ call selection + vmov s0,r0 +2: + ldr r0,iAdrsZoneConv @ conversion float in decimal string + bl convertirFloat + mov r0,#3 @ and display result + ldr r1,iAdrszMessResultValue + ldr r2,iAdrsZoneConv + ldr r3,iAdrszCarriageReturn + bl displayStrings +100: @ end function + pop {r1-r5,pc} @ restaur register +/***************************************************/ +/* Appel récursif selection */ +/***************************************************/ +/* r0 contains the address of table */ +/* r1 contains index of first item */ +/* r2 contains index of last item */ +/* r3 contains search index */ +/* r0 return final value in float */ +/* remark : the final result is a float returned in r0 register */ +select: + push {r1-r6,lr} @ save registers + mov r6,r3 @ save search index + cmp r1,r2 @ first = last ? + ldreq r0,[r0,r1,lsl #2] @ return value of first index + beq 100f @ yes -> end + add r3,r1,r2 + lsr r3,r3,#1 @ compute median pivot + mov r4,r0 @ save r0 + mov r5,r2 @ save r2 + bl partition @ cutting into 2 parts + cmp r6,r0 @ pivot is ok ? + ldreq r0,[r4,r0,lsl #2] @ return value + beq 100f + bgt 1f + sub r2,r0,#1 @ index partition - 1 + mov r0,r4 @ array address + mov r3,r6 @ search index + bl select @ select lower part + b 100f +1: + add r1,r0,#1 @ index begin = index partition + 1 + mov r0,r4 @ array address + mov r2,r5 @ last item + mov r3,r6 @ search index + bl select @ select higter part + 100: @ end function + pop {r1-r6,pc} @ restaur register +/******************************************************************/ +/* Partition table elements */ +/******************************************************************/ +/* r0 contains the address of table */ +/* r1 contains index of first item */ +/* r2 contains index of last item */ +/* r3 contains index of pivot */ +partition: + push {r1-r6,lr} @ save registers + ldr r4,[r0,r3,lsl #2] @ load value of pivot + ldr r5,[r0,r2,lsl #2] @ load value last index + str r5,[r0,r3,lsl #2] @ swap value of pivot + str r4,[r0,r2,lsl #2] @ and value last index + mov r3,r1 @ init with first index +1: @ begin loop + ldr r6,[r0,r3,lsl #2] @ load value + cmp r6,r4 @ compare loop value and pivot value + ldrlt r5,[r0,r1,lsl #2] @ if < swap value table + strlt r6,[r0,r1,lsl #2] + strlt r5,[r0,r3,lsl #2] + addlt r1,#1 @ and increment index 1 + add r3,#1 @ increment index 2 + cmp r3,r2 @ end ? + blt 1b @ no loop + ldr r5,[r0,r1,lsl #2] @ swap value + str r4,[r0,r1,lsl #2] + str r5,[r0,r2,lsl #2] + mov r0,r1 @ return index partition +100: + pop {r1-r6,pc} + +/***************************************************/ +/* display multi strings */ +/***************************************************/ +/* r0 contains number strings address */ +/* r1 address string1 */ +/* r2 address string2 */ +/* r3 address string3 */ +/* other address on the stack */ +/* thinck to add number other address * 4 to add to the stack */ +displayStrings: @ INFO: displayStrings + push {r1-r4,fp,lr} @ save des registres + add fp,sp,#24 @ save paraméters address (6 registers saved * 4 bytes) + mov r4,r0 @ save strings number + cmp r4,#0 @ 0 string -> end + ble 100f + mov r0,r1 @ string 1 + bl affichageMess + cmp r4,#1 @ number > 1 + ble 100f + mov r0,r2 + bl affichageMess + cmp r4,#2 + ble 100f + mov r0,r3 + bl affichageMess + cmp r4,#3 + ble 100f + mov r3,#3 + sub r2,r4,#4 +1: @ loop extract address string on stack + ldr r0,[fp,r2,lsl #2] + bl affichageMess + subs r2,#1 + bge 1b +100: + pop {r1-r4,fp,pc} +/******************************************************************/ +/* Conversion Float */ +/******************************************************************/ +/* s0 contains Float */ +/* r0 contains address conversion area mini 20 charactèrs*/ +/* r0 return result length */ +convertirFloat: + push {r1-r7,lr} + vpush {s0-s2} + mov r6,r0 @ save area address + vmov r0,s0 + mov r1,#0 + vmov s1,r1 + movs r7,#0 @ result length + movs r3,#'+' + strb r3,[r6] @ sign + forcing + mov r2,r0 + lsls r2,#1 @ extraction bit 31 + bcc 1f @ positive ? + lsrs r0,r2,#1 @ raz sign if negative + movs r3,#'-' @ sign - + strb r3,[r6] +1: + adds r7,#1 @ next position + cmp r0,#0 @ case of positive or negative 0 + bne 2f + movs r3,#'0' + strb r3,[r6,r7] @ store character 0 + adds r7,#1 @ next position + movs r3,#0 + strb r3,[r6,r7] @ store 0 final + mov r0,r7 @ return length + b 100f @ and end +2: + ldr r2,iMaskExposant + mov r1,r0 + ands r1,r2 @ exposant = 255 ? + cmp r1,r2 + bne 4f + lsls r0,#10 @ bit 22 à 0 ? + bcc 3f @ yes + movs r2,#'N' @ case of Nan. store byte, if not possible store int + strb r2,[r6] @ area no aligned + movs r2,#'a' + strb r2,[r6,#1] + movs r2,#'n' + strb r2,[r6,#2] + movs r2,#0 @ 0 final + strb r2,[r6,#3] + movs r0,#3 @ return length 3 + b 100f +3: @ case infini positive or négative + movs r2,#'I' + strb r2,[r6,r7] + adds r7,#1 + movs r2,#'n' + strb r2,[r6,r7] + adds r7,#1 + movs r2,#'f' + strb r2,[r6,r7] + adds r7,#1 + movs r2,#0 + strb r2,[r6,r7] + mov r0,r7 + b 100f +4: + bl normaliserFloat + mov r5,r0 @ save exposant + VCVT.U32.f32 s2,s0 @ integer value of integer part + vmov r0,s2 @ integer part + VCVT.F32.U32 s1,s2 @ conversion float + vsub.f32 s1,s0,s1 @ extraction fract part + vldr s2,iConst1 + vmul.f32 s1,s2,s1 @ to crop it in full + + VCVT.U32.f32 s1,s1 @ integer conversion + vmov r4,s1 @ fract value + @ integer conversion in r0 + mov r2,r6 @ save address area begin + adds r6,r7 + mov r1,r6 + bl conversion10 + add r6,r0 + movs r3,#',' + strb r3,[r6] + adds r6,#1 + + mov r0,r4 @ conversion fractional part + mov r1,r6 + bl conversion10SP @ spécial routine with conservation begin 0 + add r6,r0 + subs r6,#1 + @ remove trailing zeros +5: + ldrb r0,[r6] + cmp r0,#'0' + bne 6f + subs r6,#1 + b 5b +6: + cmp r0,#',' + bne 7f + subs r6,#1 +7: + adds r6,#1 + movs r3,#'E' + strb r3,[r6] + adds r6,#1 + mov r0,r5 @ conversion exposant + mov r3,r0 + lsls r3,#1 + bcc 4f + rsbs r0,r0,#0 + movs r3,#'-' + strb r3,[r6] + adds r6,#1 +4: + mov r1,r6 + bl conversion10 + add r6,r0 + + movs r3,#0 + strb r3,[r6] + adds r6,#1 + mov r0,r6 + subs r0,r2 @ return length result + subs r0,#1 @ - 0 final + +100: + vpop {s0-s2} + pop {r1-r7,pc} +iMaskExposant: .int 0xFF<<23 +iConst1: .float 0f1E9 + +/***************************************************/ +/* normaliser float */ +/***************************************************/ +/* r0 contain float value (always positive value and <> Nan) */ +/* s0 return new value */ +/* r0 return exposant */ +normaliserFloat: + push {lr} @ save registre + vmov s0,r0 @ value float + movs r0,#0 @ exposant + vldr s1,iConstE7 @ no normalisation for value < 1E7 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 10f @ if s0 < iConstE7 + + vldr s1,iConstE32 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 1f + vldr s1,iConstE32 + vdiv.f32 s0,s0,s1 + adds r0,#32 +1: + vldr s1,iConstE16 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 2f + vldr s1,iConstE16 + vdiv.f32 s0,s0,s1 + adds r0,#16 +2: + vldr s1,iConstE8 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 3f + vldr s1,iConstE8 + vdiv.f32 s0,s0,s1 + adds r0,#8 +3: + vldr s1,iConstE4 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 4f + vldr s1,iConstE4 + vdiv.f32 s0,s0,s1 + adds r0,#4 +4: + vldr s1,iConstE2 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 5f + vldr s1,iConstE2 + vdiv.f32 s0,s0,s1 + adds r0,#2 +5: + vldr s1,iConstE1 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + blo 10f + vldr s1,iConstE1 + vdiv.f32 s0,s0,s1 + adds r0,#1 + +10: + vldr s1,iConstME5 @ pas de normalisation pour les valeurs > 1E-5 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 100f + vldr s1,iConstME31 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 11f + vldr s1,iConstE32 + + vmul.f32 s0,s0,s1 + subs r0,#32 +11: + vldr s1,iConstME15 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 12f + vldr s1,iConstE16 + vmul.f32 s0,s0,s1 + subs r0,#16 +12: + vldr s1,iConstME7 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 13f + vldr s1,iConstE8 + vmul.f32 s0,s0,s1 + subs r0,#8 +13: + vldr s1,iConstME3 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 14f + vldr s1,iConstE4 + vmul.f32 s0,s0,s1 + subs r0,#4 +14: + vldr s1,iConstME1 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 15f + vldr s1,iConstE2 + vmul.f32 s0,s0,s1 + subs r0,#2 +15: + vldr s1,iConstE0 + vcmp.f32 s0,s1 + vmrs APSR_nzcv,FPSCR + bhi 100f + vldr s1,iConstE1 + vmul.f32 s0,s0,s1 + subs r0,#1 + +100: @ fin standard de la fonction + pop {pc} @ restaur des registres +.align 2 +iConstE7: .float 0f1E7 +iConstE32: .float 0f1E32 +iConstE16: .float 0f1E16 +iConstE8: .float 0f1E8 +iConstE4: .float 0f1E4 +iConstE2: .float 0f1E2 +iConstE1: .float 0f1E1 +iConstME5: .float 0f1E-5 +iConstME31: .float 0f1E-31 +iConstME15: .float 0f1E-15 +iConstME7: .float 0f1E-7 +iConstME3: .float 0f1E-3 +iConstME1: .float 0f1E-1 +iConstE0: .float 0f1E0 +/******************************************************************/ +/* Décimal Conversion */ +/******************************************************************/ +/* r0 contain value et r1 address conversion area */ +conversion10SP: + push {r1-r6,lr} @ save registers + mov r5,r1 + mov r4,#8 + mov r2,r0 + mov r1,#10 @ conversion decimale +1: @ begin loop + mov r0,r2 @ copy number or quotients + bl division @ r0 dividende r1 divisor r2 quotient r3 remainder + add r3,#48 @ compute digit + strb r3,[r5,r4] @ store byte area address (r5) + offset (r4) + subs r4,r4,#1 @ position précedente + bge 1b @ and loop if not < zero + mov r0,#8 + mov r3,#0 + strb r3,[r5,r0] @ store 0 final +100: + pop {r1-r6,pc} @ restaur registers +/***************************************************/ +/* ROUTINES INCLUDE */ +/***************************************************/ +/* for this file see task include a file in language ARM assembly */ +.include "../affichage.inc" diff --git a/Task/B-zier-curves-Intersections/C++/b-zier-curves-intersections.cpp b/Task/B-zier-curves-Intersections/C++/b-zier-curves-intersections.cpp new file mode 100644 index 0000000000..ebc1328aa0 --- /dev/null +++ b/Task/B-zier-curves-Intersections/C++/b-zier-curves-intersections.cpp @@ -0,0 +1,133 @@ +#include +#include +#include +#include +#include +#include + +const double TOLERANCE = 0.000'000'1; +const double SPACING = 10 * TOLERANCE; + +typedef std::pair point; + +class quad_spline { +public: + quad_spline(double c0, double c1, double c2) : c0(c0), c1(c1), c2(c2) {}; + quad_spline() : c0(0.0), c1(0.0), c2(0.0) {}; + double c0, c1, c2; +}; + +class quad_curve { +public: + quad_curve(quad_spline x, quad_spline y) : x(x), y(y) {}; + quad_curve() : x(quad_spline()), y(quad_spline()) {}; + quad_spline x, y; +}; + +// de Casteljau's algorithm +void subdivide_quad_spline(const quad_spline& q, const double& t, quad_spline& u, quad_spline& v) { + const double s = 1.0 - t; + u.c0 = q.c0; + v.c2 = q.c2; + u.c1 = s * q.c0 + t * q.c1; + v.c1 = s * q.c1 + t * q.c2; + u.c2 = s * u.c1 + t * v.c1; + v.c0 = u.c2; +} + +void subdivide_quad_curve(const quad_curve& q, const double t, quad_curve& u, quad_curve& v) { + subdivide_quad_spline(q.x, t, u.x, v.x); + subdivide_quad_spline(q.y, t, u.y, v.y); +} + +bool rectangles_overlap(const double& xa0, const double& ya0, const double& xa1, const double& ya1, + const double& xb0, const double& yb0, const double& xb1, const double& yb1) { + return xb0 <= xa1 && xa0 <= xb1 && yb0 <= ya1 && ya0 <= yb1; +} + +std::tuple test_intersection(const quad_curve& p, const quad_curve& q) { + const double px_min = std::min(std::min(p.x.c0, p.x.c1), p.x.c2); + const double py_min = std::min(std::min(p.y.c0, p.y.c1), p.y.c2); + const double px_max = std::max(std::max(p.x.c0, p.x.c1), p.x.c2); + const double py_max = std::max(std::max(p.y.c0, p.y.c1), p.y.c2); + + const double qx_min = std::min(std::min(q.x.c0, q.x.c1), q.x.c2); + const double qy_min = std::min(std::min(q.y.c0, q.y.c1), q.y.c2); + const double qx_max = std::max(std::max(q.x.c0, q.x.c1), q.x.c2); + const double qy_max = std::max(std::max(q.y.c0, q.y.c1), q.y.c2); + + bool accepted = false; + bool excluded = true; + point intersect = std::make_pair(0.0, 0.0); + + if ( rectangles_overlap(px_min, py_min, px_max, py_max, qx_min, qy_min, qx_max, qy_max) ) { + excluded = false; + const double x_min = std::max(px_min, qx_min); + const double x_max = std::min(px_max, px_max); + if ( x_max - x_min <= TOLERANCE ) { + const double y_min = std::max(py_min, qy_min); + const double y_max = std::min(py_max, qy_max); + if ( y_max - y_min <= TOLERANCE ) { + accepted = true; + intersect = std::make_pair(0.5 * ( x_min + x_max ), 0.5 * ( y_min + y_max)); + } + } + } + return std::make_tuple(accepted, excluded, intersect); +} + +bool seems_to_be_duplicate(const std::vector& intersects, const point& pt) { + for ( point intersect : intersects ) { + if ( fabs(intersect.first - pt.first) < SPACING && fabs(intersect.second - pt.second) < SPACING ) { + return true; + } + } + return false; +} + +std::vector find_intersects(const quad_curve& p, const quad_curve& q) { + std::vector result; + std::stack stack; + stack.push(p); + stack.push(q); + + while ( ! stack.empty() ) { + quad_curve pp = stack.top(); + stack.pop(); + quad_curve qq = stack.top(); + stack.pop(); + + std::tuple objects = test_intersection(pp, qq); + bool accepted, excluded; + point intersect; + std::tie(accepted, excluded, intersect) = objects; + + if ( accepted ) { + if ( ! seems_to_be_duplicate(result, intersect) ) { + result.push_back(intersect); + } + } else if ( ! excluded ) { + quad_curve p0{}, q0{}, p1{}, q1{}; + subdivide_quad_curve(pp, 0.5, p0, p1); + subdivide_quad_curve(qq, 0.5, q0, q1); + for ( quad_curve item : { p0, q0, p0, q1, p1, q0, p1, q1 } ) { + stack.push(item); + } + } + } + return result; +} + +int main() { + quad_curve vertical(quad_spline(-1.0, 0.0, 1.0), quad_spline(0.0, 10.0, 0.0)); + // QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0) + quad_curve horizontal(quad_spline(2.0, -8.0, 2.0), quad_spline(1.0, 2.0, 3.0)); + // QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3) + + std::cout << "The points of intersection are:" << std::endl; + std::vector intersects = find_intersects(vertical, horizontal); + for ( const point& intersect : intersects ) { + std::cout << "( " << std::setw(9) << std::setprecision(6) << intersect.first + << ", " << intersect.second << " )" << std::endl; + } +} diff --git a/Task/B-zier-curves-Intersections/Java/b-zier-curves-intersections.java b/Task/B-zier-curves-Intersections/Java/b-zier-curves-intersections.java new file mode 100644 index 0000000000..2cfbfe3be9 --- /dev/null +++ b/Task/B-zier-curves-Intersections/Java/b-zier-curves-intersections.java @@ -0,0 +1,145 @@ +import java.util.ArrayList; +import java.util.List; +import java.util.Stack; + +public final class BezierCurveIntersection { + + public static void main(String[] aArgs) { + QuadCurve vertical = new QuadCurve( new QuadSpline(-1.0, 0.0, 1.0), new QuadSpline(0.0, 10.0, 0.0) ); + // QuadCurve vertical represents the Bezier curve having control points (-1, 0), (0, 10) and (1, 0) + QuadCurve horizontal = new QuadCurve( new QuadSpline(2.0, -8.0, 2.0), new QuadSpline(1.0, 2.0, 3.0) ); + // QuadCurve horizontal represents the Bezier curve having control points (2, 1), (-8, 2) and (2, 3) + + System.out.println("The points of intersection are:"); + List intersects = findIntersects(vertical, horizontal); + for ( Point intersect : intersects ) { + System.out.println(String.format("%s%9.6f%s%9.6f%s", "( ", intersect.aX, ", ", intersect.aY, " )")); + } + } + + private static List findIntersects(QuadCurve aP, QuadCurve aQ) { + List result = new ArrayList(); + Stack stack = new Stack(); + stack.push(aP); + stack.push(aQ); + + while ( ! stack.isEmpty() ) { + QuadCurve pp = stack.pop(); + QuadCurve qq = stack.pop(); + List objects = testIntersection(pp, qq); + final boolean accepted = (boolean) objects.get(0); + final boolean excluded = (boolean) objects.get(1); + Point intersect = (Point) objects.get(2); + + if ( accepted ) { + if ( ! seemsToBeDuplicate(result, intersect) ) { + result.add(intersect); + } + } else if ( ! excluded ) { + QuadCurve p0 = new QuadCurve(); + QuadCurve q0 = new QuadCurve(); + QuadCurve p1 = new QuadCurve(); + QuadCurve q1 = new QuadCurve(); + subdivideQuadCurve(pp, 0.5, p0, p1); + subdivideQuadCurve(qq, 0.5, q0, q1); + stack.addAll(List.of( p0, q0, p0, q1, p1, q0, p1, q1 )); + } + } + return result; + } + + private static boolean seemsToBeDuplicate(List aIntersects, Point aPoint) { + for ( Point intersect : aIntersects ) { + if ( Math.abs(intersect.aX - aPoint.aX) < SPACING && Math.abs(intersect.aY - aPoint.aY) < SPACING ) { + return true; + } + } + return false; + } + + private static List testIntersection(QuadCurve aP, QuadCurve aQ) { + final double pxMin = Math.min(Math.min(aP.x.c0, aP.x.c1), aP.x.c2); + final double pyMin = Math.min(Math.min(aP.y.c0, aP.y.c1), aP.y.c2); + final double pxMax = Math.max(Math.max(aP.x.c0, aP.x.c1), aP.x.c2); + final double pyMax = Math.max(Math.max(aP.y.c0, aP.y.c1), aP.y.c2); + + final double qxMin = Math.min(Math.min(aQ.x.c0, aQ.x.c1), aQ.x.c2); + final double qyMin = Math.min(Math.min(aQ.y.c0, aQ.y.c1), aQ.y.c2); + final double qxMax = Math.max(Math.max(aQ.x.c0, aQ.x.c1), aQ.x.c2); + final double qyMax = Math.max(Math.max(aQ.y.c0, aQ.y.c1), aQ.y.c2); + + boolean accepted = false; + boolean excluded = true; + Point intersect = new Point(0.0, 0.0); + + if ( rectanglesOverlap(pxMin, pyMin, pxMax, pyMax, qxMin, qyMin, qxMax, qyMax) ) { + excluded = false; + final double xMin = Math.max(pxMin, qxMin); + final double xMax = Math.min(pxMax, pxMax); + if ( xMax - xMin <= TOLERANCE ) { + final double yMin = Math.max(pyMin, qyMin); + final double yMax = Math.min(pyMax, qyMax); + if ( yMax - yMin <= TOLERANCE ) { + accepted = true; + intersect = new Point(0.5 * ( xMin + xMax), 0.5 * ( yMin + yMax)); + } + } + } + return List.of( accepted, excluded, intersect ); + } + + private static boolean rectanglesOverlap(double aXa0, double aYa0, double aXa1, double aYa1, + double aXb0, double aYb0, double aXb1, double aYb1) { + return aXb0 <= aXa1 && aXa0 <= aXb1 && aYb0 <= aYa1 && aYa0 <= aYb1; + } + + private static void subdivideQuadCurve(QuadCurve aQ, double aT, QuadCurve aU, QuadCurve aV) { + subdivideQuadSpline(aQ.x, aT, aU.x, aV.x); + subdivideQuadSpline(aQ.y, aT, aU.y, aV.y); + } + + // de Casteljau's algorithm + private static void subdivideQuadSpline(QuadSpline aQ, double aT, QuadSpline aU, QuadSpline aV) { + final double s = 1.0 - aT; + aU.c0 = aQ.c0; + aV.c2 = aQ.c2; + aU.c1 = s * aQ.c0 + aT * aQ.c1; + aV.c1 = s * aQ.c1 + aT * aQ.c2; + aU.c2 = s * aU.c1 + aT * aV.c1; + aV.c0 = aU.c2; + } + + private static record Point(double aX, double aY) {} + + private static class QuadSpline { + + public QuadSpline(double aC0, double aC1, double aC2) { + c0 = aC0; c1 = aC1; c2 = aC2; + } + + public QuadSpline() { + this(0.0, 0.0, 0.0); + } + + private double c0, c1, c2; + + } + + private static class QuadCurve { + + public QuadCurve(QuadSpline aX, QuadSpline aY) { + x = aX; y = aY; + } + + public QuadCurve() { + this( new QuadSpline(), new QuadSpline() ); + } + + private QuadSpline x, y; + + } + + private static final double TOLERANCE = 0.000_000_1; + private static final double SPACING = 10 * TOLERANCE; + +} diff --git a/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx b/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx index 06c3e7d028..bb11547520 100644 --- a/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx +++ b/Task/Caesar-cipher/REXX/caesar-cipher-1.rexx @@ -1,22 +1,35 @@ -/*REXX program supports the Caesar cypher for the Latin alphabet only, no punctuation */ -/*──────────── or blanks allowed, all lowercase Latin letters are treated as uppercase.*/ -parse arg key .; arg . p /*get key & uppercased text to be used.*/ -p= space(p, 0) /*elide any and all spaces (blanks). */ - say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/ - say ' plain text:' p /* " " plain text " " */ -y= Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */ -z= Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */ -if z\==p then say "plain text doesn't match uncyphered cyphered text." -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Caesar: procedure; arg s,k; @= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' - ak= abs(k) /*obtain the absolute value of the key.*/ - L= length(@) /*obtain the length of the @ string. */ - if ak>length(@)-1 | k==0 then call err k 'key is invalid.' - _= verify(s, @) /*any illegal characters specified ? */ - if _\==0 then call err 'unsupported character:' substr(s, _, 1) - if k>0 then ky= k + 1 /*either cypher it, or ··· */ - else ky= L + 1 - ak /* decypher it. */ - return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -err: say; say '***error***'; say; say arg(1); say; exit 13 +/*REXX program supports the Caesar cipher for the Latin alphabet only, */ +/* no punctuation or blanks allowed, lowercase is treated as uppercase. */ +Parse Upper Arg key text /* get key & uppercased text to be ciphered*/ +text=space(text,0) /* elide any and blanks */ +Say 'Caesar cipher key:' key /* echo the Caesar cipher key */ +Say ' plain text:' text /* " " plain text */ +code=caesar(text,key) +Say ' ciphered:' code /* " " ciphered text */ +back=caesar(code,-key) +Say ' unciphered:' back /* " " unciphered text */ +If back\==text Then + Say "unciphered text doesn't match plain text." +Exit /* stick a fork in it, we're all done*/ +/*----------------------------------------------------------------------*/ +caesar: Procedure + Parse Arg text,key + abc='ABCDEFGHIJKLMNOPQRSTUVWXYZ' + If abs(key)>length(abc)-1|key==0 Then + Call err 'key ('key') is invalid.' + badpos=verify(text,abc) /* any illegal character in the text */ + If badpos\==0 Then + Call err 'unsupported character:' substr(text,badpos,1) + If key>0 Then /* cipher */ + key2=key+1 + Else /* decipher */ + key2=length(abc)+key+1 + Return translate(text,substr(abc||abc,key2,length(abc)),abc) +/*----------------------------------------------------------------------*/ +err: + Say + Say '***error***' + Say + Say arg(1) + Say + Exit 13 diff --git a/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx b/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx index 6aa291ac4d..e548c94eaf 100644 --- a/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx +++ b/Task/Caesar-cipher/REXX/caesar-cipher-2.rexx @@ -1,22 +1,39 @@ -/*REXX program supports the Caesar cypher for most keyboard characters including blanks.*/ -parse arg key p /*get key and the text to be cyphered. */ - say 'Caesar cypher key:' key /*echo the Caesar cypher key to console*/ - say ' plain text:' p /* " " plain text " " */ -y= Caesar(p, key); say ' cyphered:' y /* " " cyphered text " " */ -z= Caesar(y,-key); say ' uncyphered:' z /* " " uncyphered text " " */ -if z\==p then say "plain text doesn't match uncyphered cyphered text." -exit 0 /*stick a fork in it, we're all done. */ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -Caesar: procedure; parse arg s,k; @= 'abcdefghijklmnopqrstuvwxyz' - @= translate(@)@"0123456789(){}[]<>'" /*add uppercase, digits, group symbols.*/ - @= @'~!@#$%^&*_+:";?,./`-= ' /*also add other characters to the list*/ - L= length(@) /*obtain the length of the @ string. */ - ak= abs(k) /*obtain the absolute value of the key.*/ - if ak>length(@)-1 | k==0 then call err k 'key is invalid.' - _= verify(s,@) /*any illegal characters specified ? */ - if _\==0 then call err 'unsupported character:' substr(s, _, 1) - if k>0 then ky= k + 1 /*either cypher it, or ··· */ - else ky= L + 1 - ak /* decypher it. */ - return translate(s, substr(@ || @, ky, L), @) /*return the processed text.*/ -/*──────────────────────────────────────────────────────────────────────────────────────*/ -err: say; say '***error***'; say; say arg(1); say; exit 13 +/*REXX program supports the Caesar cipher for most keyboard characters */ +/* including blanks.*/ + Parse Arg key text /* get key and the text to be ciph */ + Say 'Caesar cipher key:' key /* echo the Caesar cipher key */ + Say ' plain text:' text /* " " plain text */ + code=caesar(text,key) + Say ' ciphered:' code /* " " ciphered text */ + back=caesar(code,-key) + Say ' unciphered:' back /* " " unciphered text */ + If back\==text Then + Say "plain text doesn't match unciphered ciphered text." + Exit /* stick a fork in it, we're all done */ +/*----------------------------------------------------------------------*/ +caesar: Procedure + Parse Arg txt,ky + abcx='abcdefghijklmnopqrstuvwxyz' + abcx=translate(abcx)abcx"0123456789(){}[]<>'" /*add uppercase, digits */ + abcx=abcx'~!@#$%^&*_+:";?,./`-= ' /* also add other characters */ + l=length(abcx) /* obtain the length of abcx */ + aky=abs(ky) /* absolute value of the key */ + If aky>length(abcx)-1|ky==0 Then + Call err ky 'key is invalid.' + badpos=verify(txt,abcx) /* any illegal character in txt */ + If badpos\==0 Then + Call err 'unsupported character:' substr(txt,badpos,1) + If ky>0 Then /* cipher */ + ky=ky+1 + Else /* decipher */ + ky=l+1-aky + /* return translated input */ + Return translate(txt,substr(abcx||abcx,ky,l),abcx) +/*----------------------------------------------------------------------*/ +err: + Say + Say '***error***' + Say + Say arg(1) + Say + Exit 13 diff --git a/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic new file mode 100644 index 0000000000..97b62bc879 --- /dev/null +++ b/Task/Canonicalize-CIDR/FreeBASIC/canonicalize-cidr.basic @@ -0,0 +1,54 @@ +#lang "qb" + +REM THE Binary OPS ONLY WORK On SIGNED 16-Bit NUMBERS +REM SO WE STORE THE IP ADDRESS As AN ARRAY OF FOUR OCTETS +Cls +Dim IP(3) +Do + REM Read DEMO Data + 140 Read CI$ + If CI$ = "" Then Exit Do 'Sleep: End + REM FIND / + SL = 0 + For I = Len(CI$) To 1 Step -1 + If Mid$(CI$,I,1) = "/" Then SL = I : I = 1 + Next I + If SL = 0 Then Print "INVALID CIDR STRING: '"; CI$; "'": Goto 140 + NW = Val(Mid$(CI$,SL+1)) + If NW < 1 Or NW > 32 Then Print "INVALID NETWORK WIDTH:"; NW: Goto 140 + REM PARSE OCTETS INTO IP ARRAY + BY = 0 : N = 0 + For I = 1 To SL-1 + C$ = Mid$(CI$,I,1) + If Not (C$ <> ".") Then + IP(N) = BY : N = N + 1 + BY = 0 + If IP(N-1) < 256 Then 310 + Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140 + Else C = Val(C$):If C Or (C$="0") Then BY = BY*10+C + End If + 310 ' + Next I + IP(N) = BY : N = N + 1 + If IP(N-1) > 255 Then Print "INVALID OCTET VALUE:"; IP(N-1): Goto 140 + REM NUMBER OF COMPLETE OCTETS IN NETWORK PART + NB = Int(NW/8) + REM NUMBER OF NETWORK BITS IN PARTIAL OCTET + XB = NW And 7 + REM ZERO Out HOST BITS IN PARTIAL OCTET + IP(NB) = IP(NB) And (255 - 2^(8-XB) + 1) + REM And SET Any ALL-HOST OCTETS To 0 + If NB < 3 Then For I = NB +1 To 3 : IP(I) = 0 : Next I + REM Print Out THE RESULT + Print Mid$(Str$(IP(0)),2); + For I = 1 To 3 + Print "."; Mid$(Str$(IP( I)),2); + Next I + Print Mid$(CI$,SL) +Loop +Data "87.70.141.1/22", "36.18.154.103/12", "62.62.197.11/29" +Data "67.137.119.181/4", "161.214.74.21/24", "184.232.176.184/18" +REM SOME INVALID INPUTS +Data "127.0.0.1", "123.45.67.89/0", "98.76.54.32/100", "123.456.789.0/12" + +Sleep diff --git a/Task/Canonicalize-CIDR/QBasic/canonicalize-cidr.basic b/Task/Canonicalize-CIDR/QBasic/canonicalize-cidr.basic new file mode 100644 index 0000000000..404435b6fa --- /dev/null +++ b/Task/Canonicalize-CIDR/QBasic/canonicalize-cidr.basic @@ -0,0 +1,44 @@ +CLS +DIM IP(3) +DO + REM Read DEMO Data +140 READ CI$ + IF CI$ = "" THEN EXIT DO 'Sleep: End + REM FIND / + SL = 0 + FOR I = LEN(CI$) TO 1 STEP -1 + IF MID$(CI$, I, 1) = "/" THEN SL = I: I = 1 + NEXT I + IF SL = 0 THEN PRINT "INVALID CIDR STRING: '"; CI$; "'": GOTO 140 + NW = VAL(MID$(CI$, SL + 1)) + IF NW < 1 OR NW > 32 THEN PRINT "INVALID NETWORK WIDTH:"; NW: GOTO 140 + REM PARSE OCTETS INTO IP ARRAY + BY = 0: N = 0 + FOR I = 1 TO SL - 1 + C$ = MID$(CI$, I, 1): IF C$ <> "." THEN 300 + IP(N) = BY: N = N + 1: BY = 0: IF IP(N - 1) < 256 THEN 310 +290 PRINT "INVALID OCTET VALUE:"; IP(N - 1): GOTO 140 +300 C = VAL(C$): IF C OR (C$ = "0") THEN BY = BY * 10 + C +310 ' + NEXT I + IP(N) = BY: N = N + 1: IF IP(N - 1) > 255 THEN 290 + REM NUMBER OF COMPLETE OCTETS IN NETWORK PART + NB = INT(NW / 8) + REM NUMBER OF NETWORK BITS IN PARTIAL OCTET + XB = NW AND 7 + REM ZERO Out HOST BITS IN PARTIAL OCTET + IP(NB) = IP(NB) AND (255 - 2 ^ (8 - XB) + 1) + REM And SET Any ALL-HOST OCTETS To 0 + IF NB < 3 THEN FOR I = NB + 1 TO 3: IP(I) = 0: NEXT I + REM Print Out THE RESULT + PRINT MID$(STR$(IP(0)), 2); + FOR I = 1 TO 3 + PRINT "."; MID$(STR$(IP(I)), 2); + NEXT I + PRINT MID$(CI$, SL) +LOOP +DATA 87.70.141.1/22, 36.18.154.103/12, 62.62.197.11/29 +DATA 67.137.119.181/4, 161.214.74.21/24, 184.232.176.184/18 +REM SOME INVALID INPUTS +DATA 127.0.0.1, 123.45.67.89/0, 98.76.54.32/100, 123.456.789.0/12 +DATA diff --git a/Task/Cistercian-numerals/Rust/cistercian-numerals.rust b/Task/Cistercian-numerals/Rust/cistercian-numerals.rust new file mode 100644 index 0000000000..01e406897c --- /dev/null +++ b/Task/Cistercian-numerals/Rust/cistercian-numerals.rust @@ -0,0 +1,150 @@ +use once_cell::sync::Lazy; + +const GRID_SIZE: usize = 15; +static mut CANVAS: Lazy> = Lazy::new(|| vec![[' '; GRID_SIZE]; GRID_SIZE],); + +/// initialize CANVAS +fn init_n() { + for i in 0..GRID_SIZE { + for j in 0..GRID_SIZE { + unsafe { CANVAS[i][j] = ' '; } + } + unsafe { CANVAS[i][5] = '#'; } + } +} + +/// draw horizontal +fn horizontal(c1: usize, c2: usize, r: usize) { + for c in c1..=c2 { + unsafe { CANVAS[r][c] = '#'; } + } +} + +/// draw vertical +fn vertical(r1: usize, r2: usize, c: usize) { + for r in r1..=r2 { + unsafe { CANVAS[r][c] = '#'; } + } +} + +/// draw diagonal NE to SW +fn diag_d(c1 : usize, c2: usize, r: usize) { + for c in c1..=c2 { + unsafe { CANVAS[r + c - c1][c] = '#'; } + } +} + +/// draw diagonal SE to NW +fn diag_u(c1: usize, c2: usize, r: usize) { + for c in c1..=c2 { + unsafe { CANVAS[r + c1 - c][c] = '#'; } + } +} + +/// Mark the portions of the ones place. +fn draw_ones(v: i32) { + match v { + 1 => horizontal(6, 10, 0), + 2 => horizontal(6, 10, 4), + 3 => diag_d(6, 10, 0), + 4 => diag_u(6, 10, 4), + 5 => { draw_ones(1); draw_ones(4); }, + 6 => vertical(0, 4, 10), + 7 => { draw_ones(1); draw_ones(6); }, + 8 => { draw_ones(2); draw_ones(6); }, + 9 => { draw_ones(1); draw_ones(8); }, + _ => {}, + } +} + +/// Mark the portions of the tens place. +fn draw_tens(v: i32) { + match v { + 1 => horizontal(0, 4, 0), + 2 => horizontal(0, 4, 4), + 3 => diag_u(0, 4, 4), + 4 => diag_d(0, 4, 0), + 5 => { draw_tens(1); draw_tens(4); }, + 6 => vertical(0, 4, 0), + 7 => { draw_tens(1); draw_tens(6); }, + 8 => { draw_tens(2); draw_tens(6); }, + 9 => { draw_tens(1); draw_tens(8); }, + _ => {}, + } +} + +/// Mark the portions of the hundreds place. +fn draw_hundreds(hundreds: i32) { + match hundreds { + 1 => horizontal(6, 10, 14), + 2 => horizontal(6, 10, 10), + 3 => diag_u(6, 10, 14), + 4 => diag_d(6, 10, 10), + 5 => { draw_hundreds(1); draw_hundreds(4) }, + 6 => vertical(10, 14, 10), + 7 => { draw_hundreds(1); draw_hundreds(6); }, + 8 => { draw_hundreds(2); draw_hundreds(6); }, + 9 => { draw_hundreds(1); draw_hundreds(8); }, + _ => {}, + } +} + +/// Mark the portions of the thousands place. +fn draw_thousands(thousands: i32) { + match thousands { + 1 => horizontal(0, 4, 14), + 2 => horizontal(0, 4, 10), + 3 => diag_d(0, 4, 10), + 4 => diag_u(0, 4, 14), + 5 => { draw_thousands(1); draw_thousands(4); }, + 6 => vertical(10, 14, 0), + 7 => { draw_thousands(1); draw_thousands(6); }, + 8 => { draw_thousands(2); draw_thousands(6); }, + 9 => { draw_thousands(1); draw_thousands(8); }, + _ => {}, + } +} + +/// Mark the char matrix for the numeral drawing. +fn draw(mut v: i32) { + let thousands: i32 = v / 1000; + v %= 1000; + let hundreds: i32 = v / 100; + v %= 100; + let tens: i32 = v / 10; + let ones: i32 = v % 10; + if thousands > 0 { + draw_thousands(thousands); + } + if hundreds > 0 { + draw_hundreds(hundreds); + } + if tens > 0 { + draw_tens(tens); + } + if ones > 0 { + draw_ones(ones); + } +} + +/// Test the drawings as outout to stdout. +fn test_output(n: i32) { + println!("{n}"); + init_n(); + draw(n); + unsafe { + for line in CANVAS.iter() { + for c in line.iter() { + print!("{}", *c); + } + println!(); + } + } + println!("\n"); +} + +fn main() { + for n in [0, 1, 20, 300, 2022, 4000, 5555, 6789, 9999] { + test_output(n); + } +} diff --git a/Task/Color-quantization/Java/color-quantization.java b/Task/Color-quantization/Java/color-quantization.java new file mode 100644 index 0000000000..29475ff073 --- /dev/null +++ b/Task/Color-quantization/Java/color-quantization.java @@ -0,0 +1,127 @@ +import java.awt.Color; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import javax.imageio.ImageIO; + +public final class ColorQuantization { + + public static void main(String[] aArgs) throws IOException { + BufferedImage original = ImageIO.read( new File("quantum_frog.png") ); + final int width = original.getWidth(); + final int height = original.getHeight(); + int[] originalPixels = original.getRGB(0, 0, width, height, null, 0, width); + + List bucket = new ArrayList(); + for ( int i = 0; i < originalPixels.length; i++ ) { + bucket.add( new Item(new Color(originalPixels[i]), i) ); + } + + int[] resultPixels = new int[originalPixels.length]; + medianCut(bucket, 4, resultPixels); + + BufferedImage result = new BufferedImage(width, height, original.getType()); + result.setRGB(0, 0, width, height, resultPixels, 0, width); + ImageIO.write(result, "png", new File("Quantum_frog16Java.png")); + + System.out.println("The 16 colors used in Red, Green, Blue format are:"); + for ( Color color : colorsUsed ) { + System.out.println("(" + color.getRed() + ", " + color.getGreen() + ", " + color.getBlue() + ")"); + } + } + + private static void medianCut(List aBucket, int aDepth, int[] aResultPixels) { + if ( aDepth == 0 ) { + quantize(aBucket, aResultPixels); + return; + } + + int[] minimumValue = new int[] { 256, 256, 256 }; + int[] maximumValue = new int[] { 0, 0, 0 }; + for ( Item item : aBucket ) { + for ( Channel channel : Channel.values() ) { + int value = item.getPrimary(channel); + if ( value < minimumValue[channel.index] ) { + minimumValue[channel.index] = value; + } + if ( value > maximumValue[channel.index] ) { + maximumValue[channel.index] = value; + } + } + } + + int[] valueRange = new int[] { maximumValue[Channel.RED.index] - minimumValue[Channel.RED.index], + maximumValue[Channel.GREEN.index] - minimumValue[Channel.GREEN.index], + maximumValue[Channel.BLUE.index] - minimumValue[Channel.BLUE.index] }; + + Channel selectedChannel = ( valueRange[Channel.RED.index] >= valueRange[Channel.GREEN.index] ) + ? ( valueRange[Channel.RED.index] >= valueRange[Channel.BLUE.index] ) ? Channel.RED : Channel.BLUE + : ( valueRange[Channel.GREEN.index] >= valueRange[Channel.BLUE.index] ) ? Channel.GREEN : Channel.BLUE; + + Collections.sort(aBucket, switch(selectedChannel) { + case RED -> redComparator; + case GREEN -> greenComparator; + case BLUE -> blueComparator; }); + + final int medianIndex = aBucket.size() / 2; + medianCut(new ArrayList(aBucket.subList(0, medianIndex)), aDepth - 1, aResultPixels); + medianCut(new ArrayList(aBucket.subList(medianIndex, aBucket.size())), aDepth - 1, aResultPixels); + } + + private static void quantize(List aBucket, int[] aResultPixels) { + int[] means = new int[Channel.values().length]; + for ( Item item : aBucket ) { + for ( Channel channel : Channel.values() ) { + means[channel.index] += item.getPrimary(channel); + } + } + + for ( Channel channel : Channel.values() ) { + means[channel.index] /= aBucket.size(); + } + + Color color = new Color(means[Channel.RED.index], means[Channel.GREEN.index], means[Channel.BLUE.index]); + colorsUsed.add(color); + + for ( Item item : aBucket ) { + aResultPixels[item.aIndex] = color.getRGB(); + } + } + + private enum Channel { + RED(0), GREEN(1), BLUE(2); + + private Channel(int aIndex) { + index = aIndex; + } + + private final int index; + } + + private record Item(Color aColor, Integer aIndex) { + + public int getPrimary(Channel aChannel) { + return switch(aChannel) { + case RED -> aColor.getRed(); + case GREEN -> aColor.getGreen(); + case BLUE -> aColor.getBlue(); + }; + } + + } + + private static Comparator redComparator = + (one, two) -> Integer.compare(one.aColor.getRed(), two.aColor.getRed()); + private static Comparator greenComparator = + (one, two) -> Integer.compare(one.aColor.getGreen(), two.aColor.getGreen()); + private static Comparator blueComparator = + (one, two) -> Integer.compare(one.aColor.getBlue(), two.aColor.getBlue()); + + private static List colorsUsed = new ArrayList(); + +} diff --git a/Task/Colorful-numbers/C++/colorful-numbers.cpp b/Task/Colorful-numbers/C++/colorful-numbers.cpp index 8a3d19948c..403ca45cc9 100644 --- a/Task/Colorful-numbers/C++/colorful-numbers.cpp +++ b/Task/Colorful-numbers/C++/colorful-numbers.cpp @@ -7,7 +7,7 @@ std::vector count(8, 0); std::vector used(10, false); uint32_t largest = 0; -bool is_colorful(uint32_t number) { +bool is_colorful(const uint32_t& number) { if ( number > 98'765'432 ) { return false; } @@ -42,7 +42,7 @@ bool is_colorful(uint32_t number) { return true; } -void count_colorful(uint32_t taken, uint32_t number, uint32_t digits) { +void count_colorful(const uint32_t& taken, const uint32_t& number, const uint32_t& digits) { if ( taken == 0 ) { for ( uint32_t digit = 0; digit < 10; ++digit ) { used[digit] = true; diff --git a/Task/Colorful-numbers/Rust/colorful-numbers.rust b/Task/Colorful-numbers/Rust/colorful-numbers.rust new file mode 100644 index 0000000000..f42bdf8bdd --- /dev/null +++ b/Task/Colorful-numbers/Rust/colorful-numbers.rust @@ -0,0 +1,73 @@ +use core::cmp::max; +use std::collections::HashSet; + +fn to_digits(mut n: u64, base: u64) -> Vec { + if n == 0 { + return [0].to_vec(); + } + let mut v: Vec = Vec::new(); + while n > 0 { + let d = n % base; + n /= base; + v.push(d); + } + return v; +} + +fn is_colorful(n: u64) -> bool { + if &n > &9 { + let dig: Vec = to_digits(n, 10); + if dig.contains(&1) || dig.contains(&0) { + return false; + } + let mut products: HashSet = HashSet::new(); + for i in 0..dig.len() { + if products.contains(&dig[i]) { + return false; + } + products.insert(dig[i]); + } + for i in 0..dig.len() { + for j in i+2..dig.len()+1 { + let p: u64 = (dig[i..j]).iter().product(); + if products.contains(&p) { + return false; + } + products.insert(p); + } + } + } + return true; +} + +fn main() { + println!("Colorful numbers for 1:25, 26:50, 51:75, and 76:100:"); + for i in (1..101).step_by(25) { + for j in 0..25 { + if is_colorful(i + j) { + print!("{:5}", i + j); + } + } + println!(); + } + println!(); + + let mut csum: u64 = 0; + let mut largest: u64 = 0; + let mut n: u64; + for i in 0..8 { + let j: u64 = { if i == 0 { 0 } else { 10_u64.pow(i) } }; + let k: u64 = 10_u64.pow(i + 1) - 1; + n = 0; + for x in j..k+1 { + if is_colorful(x) { + largest = max(largest, x); + n += 1; + } + } + println!("The count of colorful numbers within the interval [{j}, {k}] is {n}."); + csum += n; + } + println!("The largest possible colorful number is {largest}."); + println!("The total number of colorful numbers is {csum}.") +} diff --git a/Task/Comma-quibbling/Sidef/comma-quibbling.sidef b/Task/Comma-quibbling/Sidef/comma-quibbling.sidef index a683c3d8f2..c41b243099 100644 --- a/Task/Comma-quibbling/Sidef/comma-quibbling.sidef +++ b/Task/Comma-quibbling/Sidef/comma-quibbling.sidef @@ -1,7 +1,7 @@ func comma_quibbling(words) { - '{' + ([words.ft(0, -2).join(', ')]-[''] + [words.last] -> join(' and ')) + '}'; + '{' + ([words.first(-1).join(', ')]-[''] + [words.last] -> join(' and ')) + '}' } [<>, , , ].each { |w| - say comma_quibbling(w); + say comma_quibbling(w) } diff --git a/Task/Comments/EMal/comments.emal b/Task/Comments/EMal/comments.emal new file mode 100644 index 0000000000..0742232c4f --- /dev/null +++ b/Task/Comments/EMal/comments.emal @@ -0,0 +1,9 @@ +# This is a line comment. +^|This is a single line block comment.|^ + +^| This is + | a multi-line + | block comment. + |^ + +^|This is a ^|nested|^ block comment.|^ diff --git a/Task/Compile-time-calculation/Java/compile-time-calculation.java b/Task/Compile-time-calculation/Java/compile-time-calculation.java new file mode 100644 index 0000000000..5925bc4e2b --- /dev/null +++ b/Task/Compile-time-calculation/Java/compile-time-calculation.java @@ -0,0 +1,9 @@ +public final class CompileTimeCalculation { + + public static void main(String[] aArgs) { + System.out.println(tenFactorial); + } + + private static int tenFactorial = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1; + +} diff --git a/Task/Compile-time-calculation/Raku/compile-time-calculation-2.raku b/Task/Compile-time-calculation/Raku/compile-time-calculation-2.raku index 2fcd6de3a4..2149de8867 100644 --- a/Task/Compile-time-calculation/Raku/compile-time-calculation-2.raku +++ b/Task/Compile-time-calculation/Raku/compile-time-calculation-2.raku @@ -1 +1 @@ - say(BEGIN [*] 2..10); + say BEGIN [*] 2..10; diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.c b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.c new file mode 100644 index 0000000000..f9ef138886 --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/C/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.c @@ -0,0 +1,44 @@ +#include +#include + +bool is_substring(unsigned n, unsigned k) { + unsigned startMatch = 0; + + for (unsigned pfx = k; n > 0; n /= 10) { + if (pfx % 10 == n % 10) { + pfx /= 10; + if (startMatch == 0) startMatch = n; + } else { + pfx = k; + if (startMatch != 0) n = startMatch; + startMatch = 0; + } + + if (pfx == 0) return true; + } + return false; +} + +bool factors_are_substrings(unsigned n) { + if (n%2==0 || n%3==0 || n%5==0 || n%7==0) return false; + + unsigned factor_count = 0; + for (unsigned factor = 11, n_rest = n; factor <= n_rest; factor += 2) { + if (n_rest % factor != 0) continue; + while (n_rest % factor == 0) n_rest /= factor; + if (!is_substring(n, factor)) return false; + factor_count++; + } + return factor_count > 1; +} + +int main(void) { + unsigned amount = 10; + for (unsigned n = 11; amount > 0; n += 2) { + if (factors_are_substrings(n)) { + printf("%u\n", n); + amount--; + } + } + return 0; +} diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java new file mode 100644 index 0000000000..a7399b3eae --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Java/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.java @@ -0,0 +1,74 @@ +import java.math.BigInteger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.ThreadLocalRandom; + +public final class CompositeNumbersK { + + public static void main(String[] aArgs) { + int k = 11 * 11; + List result = new ArrayList(); + while ( result.size() < 20 ) { + while ( k % 3 == 0 || k % 5 == 0 || k % 7 == 0 ) { + k += 2; + } + + List factors = primeFactors(k); + if ( factors.size() > 1 ) { + String stringK = String.valueOf(k); + if ( factors.stream().allMatch( factor -> stringK.indexOf(String.valueOf(factor)) >= 0 ) ) { + result.add(k); + } + } + k += 2; + } + + for ( int i = 0; i < result.size(); i++ ) { + System.out.print(String.format("%10d%s", result.get(i), ( i == 9 || i == 19 ? "\n" : "" ))); + } + } + + private static List primeFactors(int aK) { + ArrayList result = new ArrayList(); + if ( aK <= 1 ) { + return result; + } + + BigInteger bigK = BigInteger.valueOf(aK); + if ( bigK.isProbablePrime(CERTAINTY_LEVEL) ) { + result.add(aK); + return result; + } + + int divisor = pollardsRho(bigK).intValueExact(); + result.addAll(primeFactors(divisor)); + result.addAll(primeFactors(aK / divisor)); + Collections.sort(result); + return result; + } + + private static BigInteger pollardsRho(BigInteger aN) { + final BigInteger constant = new BigInteger(aN.bitLength(), RANDOM); + BigInteger x = new BigInteger(aN.bitLength(), RANDOM); + BigInteger xx = x; + BigInteger divisor = null; + + if ( aN.mod(BigInteger.TWO).signum() == 0 ) { + return BigInteger.TWO; + } + + do { + x = x.multiply(x).mod(aN).add(constant).mod(aN); + xx = xx.multiply(xx).mod(aN).add(constant).mod(aN); + xx = xx.multiply(xx).mod(aN).add(constant).mod(aN); + divisor = x.subtract(xx).gcd(aN); + } while ( divisor.compareTo(BigInteger.ONE) == 0 ); + + return divisor; + } + + private static final ThreadLocalRandom RANDOM = ThreadLocalRandom.current(); + private static final int CERTAINTY_LEVEL = 10; + +} diff --git a/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.rust b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.rust new file mode 100644 index 0000000000..aacc8237c7 --- /dev/null +++ b/Task/Composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k/Rust/composite-numbers-k-with-no-single-digit-factors-whose-factors-are-all-substrings-of-k.rust @@ -0,0 +1,25 @@ +use primes::{is_prime,factors_uniq}; + +/// True if non-prime n's factors, all > 9, are all substrings of its representation in base 10 +fn contains_its_prime_factors_all_over_7(n: u64) -> bool { + if n < 10 || is_prime(n) { + return false; + } + let strn = &n.to_string(); + let pfacs = factors_uniq(n); + return pfacs.iter().all(|f| f > &9 && strn.contains(&f.to_string())); +} + +fn main() { + let mut found = 0; + // 20 of these < 30 million + for n in 0..30_000_000 { + if contains_its_prime_factors_all_over_7(n) { + found += 1; + print!("{:12}{}", n, {if found % 10 == 0 {"\n"} else {""}}); + if found == 20 { + break; + } + } + } +} diff --git a/Task/Conditional-structures/Ol/conditional-structures-1.ol b/Task/Conditional-structures/Ol/conditional-structures-1.ol index bba83ca49f..7704a29f9d 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-1.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-1.ol @@ -1,3 +1,5 @@ -(if (= (* 2 2) 4) (print "if-then: equal")) -(if (= (* 2 2) 6) (print "if-then: non equal")) +(if (= (* 2 2) 4) + (print "if-then: equal")) +(if (= (* 2 2) 6) + (print "if-then: should not be printed")) ; ==> if-then: equal diff --git a/Task/Conditional-structures/Ol/conditional-structures-2.ol b/Task/Conditional-structures/Ol/conditional-structures-2.ol index e10e8b9d08..48e2435b0d 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-2.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-2.ol @@ -1,4 +1,9 @@ -(if (= (* 2 2) 4) (print "if-then-else: equal") (print "if-then-else: non equal")) -(if (= (* 2 2) 6) (print "if-then-else: non equal") (print "if-then-else: i don't know")) +(if (= (* 2 2) 4) + (print "if-then-else: equal") + (print "if-then-else: non equal")) ; ==> if-then-else: equal -; ==> if-then-else: i don't know + +(if (= (* 2 2) 6) + (print "if-then-else: equal") + (print "if-then-else: non equal")) +; ==> if-then-else: non equal diff --git a/Task/Conditional-structures/Ol/conditional-structures-3.ol b/Task/Conditional-structures/Ol/conditional-structures-3.ol index 50794412e8..ec093ee512 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-3.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-3.ol @@ -1,7 +1,11 @@ -(unless (= (* 2 2) 4) (print "unless: non equal")) -(unless (= (* 2 2) 6) (print "unless: i don't know")) -(unless (= (* 2 2) 4) (print "unless: non equal") (print "unless: equal")) -(unless (= (* 2 2) 6) (print "unless: i don't know") (print "unless: non equal")) -; ==> unless: i don't know -; ==> unless: equal -; ==> unless: i don't know +(when (= (* 2 2) 4) + (print "when: ..just do something..") + (print "when: equal")) +; ==> when: ..just do something.. +; ==> when: equal + +(unless (= (* 2 2) 6) + (print "unless: ..just do something..") + (print "unless: not equal")) +; ==> unless: ..just do something.. +; ==> unless: not equal diff --git a/Task/Conditional-structures/Ol/conditional-structures-4.ol b/Task/Conditional-structures/Ol/conditional-structures-4.ol index 9cc2a51886..9a8c796143 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-4.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-4.ol @@ -1,10 +1,23 @@ -(case (* 2 2) - (3 - (print "case: 3")) - (4 - (print "case: 4")) - ((5 6 7) - (print "case: 5 or 6 or 7")) - (else - (print "case: i don't know"))) -; ==> case: 4 +(if (= (* 2 2) 4) + (print "if-then-else*: equal") +else + (print "if-then-else*: ..just do something..") + (print "if-then-else*: non equal")) +; ==> if-then-else*: equal + +(if (= (* 2 2) 4) +then + (print "if-then-else*: ..just do something..") + (print "if-then-else*: equal") +else + (print "if-then-else*: ..just do something..") + (print "if-then-else*: non equal")) +; ==> if-then-else*: ..just do something.. +; ==> if-then-else*: equal + +(if (= (* 2 2) 4) ; same as `when` +then + (print "if-then-else*: ..just do something..") + (print "if-then-else*: equal")) +; ==> if-then-else*: ..just do something.. +; ==> if-then-else*: equal diff --git a/Task/Conditional-structures/Ol/conditional-structures-5.ol b/Task/Conditional-structures/Ol/conditional-structures-5.ol index 9a230fc0de..32eff25558 100644 --- a/Task/Conditional-structures/Ol/conditional-structures-5.ol +++ b/Task/Conditional-structures/Ol/conditional-structures-5.ol @@ -1,8 +1,35 @@ -(case (vector 'selector 1 2 3) +(case (* 2 2) + (3 ; exact number + (print "case: 3")) + (4 ; exact number + (print "case: 4")) + ((5 6 7) ; list of numbers + (print "case: 5 or 6 or 7")) + (else + (print "case: i don't know"))) +; ==> case: 4 + +; extended case with usable else +(case (* 2 2) + (3 ; exact number + (print "case: 3")) + (else => (lambda (num) + (print "case: real value is " num)))) +; ==> case: real value is 4 + +(case (* 2 2) + (3 ; exact number + (print "case: 3")) + (else is num + (print "case: real value is " num))) +; ==> case: real value is 4 + +; extended case with vectors +(case ['selector 1 2 3] (['case1 x y] (print "case: case1 " x ", " y)) (['selector x y z] (print "case: selector " x ", " y ", " z)) (else (print "case: i don't know"))) -; ==> tuple-case: selector 1, 2, 3 +; ==> case: selector 1, 2, 3 diff --git a/Task/Consecutive-primes-with-ascending-or-descending-differences/Java/consecutive-primes-with-ascending-or-descending-differences.java b/Task/Consecutive-primes-with-ascending-or-descending-differences/Java/consecutive-primes-with-ascending-or-descending-differences.java new file mode 100644 index 0000000000..33ceaa1e40 --- /dev/null +++ b/Task/Consecutive-primes-with-ascending-or-descending-differences/Java/consecutive-primes-with-ascending-or-descending-differences.java @@ -0,0 +1,86 @@ +import java.util.ArrayList; +import java.util.BitSet; +import java.util.List; + +public final class ConsecutivePrimes { + + public static void main(String[] aArgs) { + final int limit = 1_000_000; + List primes = listPrimeNumbers(limit); + + List asc = new ArrayList(); + List desc = new ArrayList(); + List> maxAsc = new ArrayList>(); + List> maxDesc = new ArrayList>(); + int maxAscSize = 0; + int maxDescSize = 0; + + for ( int prime : primes ) { + final int ascSize = asc.size(); + if ( ascSize > 1 && prime - asc.get(ascSize - 1) <= asc.get(ascSize - 1) - asc.get(ascSize - 2) ) { + asc = new ArrayList(asc.subList(ascSize - 1, asc.size())); + } + asc.add(prime); + + if ( asc.size() >= maxAscSize ) { + if ( asc.size() > maxAscSize ) { + maxAscSize = asc.size(); + maxAsc.clear(); + } + maxAsc.add( new ArrayList(asc) ); + } + + final int descSize = desc.size(); + if ( descSize > 1 && prime - desc.get(descSize - 1) >= desc.get(descSize - 1) - desc.get(descSize - 2) ) { + desc = new ArrayList(desc.subList(descSize - 1, desc.size())); + } + desc.add(prime); + + if ( desc.size() >= maxDescSize ) { + if ( desc.size() > maxDescSize ) { + maxDescSize = desc.size(); + maxDesc.clear(); + } + maxDesc.add( new ArrayList(desc) ); + } + } + + System.out.println("Longest run(s) of ascending prime gaps up to " + limit + ":"); + for ( List list : maxAsc ) { + displayResult(list); + } + System.out.println(); + + System.out.println("Longest run(s) of descending prime gaps up to " + limit + ":"); + for( List list : maxDesc ) { + displayResult(list); + } + } + + private static List listPrimeNumbers(int aLimit) { + BitSet sieve = new BitSet(aLimit + 1); + sieve.set(2, aLimit + 1); + for ( int i = 2; i <= Math.sqrt(aLimit); i = sieve.nextSetBit(i + 1) ) { + for ( int j = i * i; j <= aLimit; j = j + i ) { + sieve.clear(j); + } + } + + List result = new ArrayList(sieve.cardinality()); + for ( int i = 2; i >= 0; i = sieve.nextSetBit(i + 1) ) { + result.add(i); + } + return result; + } + + private static void displayResult(List aList) { + for ( int i = 0; i < aList.size(); i++ ) { + if ( i > 0 ) { + System.out.print(" (" + ( aList.get(i) - aList.get(i - 1) ) + ") "); + } + System.out.print(aList.get(i)); + } + System.out.println(); + } + +} diff --git a/Task/Curzon-numbers/Java/curzon-numbers.java b/Task/Curzon-numbers/Java/curzon-numbers.java new file mode 100644 index 0000000000..0f4634296f --- /dev/null +++ b/Task/Curzon-numbers/Java/curzon-numbers.java @@ -0,0 +1,48 @@ +public final class CurzonNumbers { + + public static void main(String[] aArgs) { + for ( int k = 2; k <= 10; k += 2 ) { + System.out.println("Generalised Curzon numbers with base " + k + ":"); + int n = 1; + int count = 0; + while ( count < 50 ) { + if ( isGeneralisedCurzonNumber(k, n) ) { + System.out.print(String.format("%4d%s", n, ( ++count % 10 == 0 ? "\n" : " " ))); + } + n += 1; + } + + while ( count < 1_000 ) { + if ( isGeneralisedCurzonNumber(k, n) ) { + count += 1; + } + n += 1; + } + System.out.println("1,000th Generalised Curzon number with base " + k + ": " + ( n - 1 )); + System.out.println(); + } + } + + private static boolean isGeneralisedCurzonNumber(int aK, int aN) { + final long r = aK * aN; + return modulusPower(aK, aN, r + 1) == r; + } + + private static long modulusPower(long aBase, long aExponent, long aModulus) { + if ( aModulus == 1 ) { + return 0; + } + + aBase %= aModulus; + long result = 1; + while ( aExponent > 0 ) { + if ( ( aExponent & 1 ) == 1 ) { + result = ( result * aBase ) % aModulus; + } + aBase = ( aBase * aBase ) % aModulus; + aExponent >>= 1; + } + return result; + } + +} diff --git a/Task/Death-Star/Java/death-star.java b/Task/Death-Star/Java/death-star-1.java similarity index 100% rename from Task/Death-Star/Java/death-star.java rename to Task/Death-Star/Java/death-star-1.java diff --git a/Task/Death-Star/Java/death-star-2.java b/Task/Death-Star/Java/death-star-2.java new file mode 100644 index 0000000000..42a7301cf1 --- /dev/null +++ b/Task/Death-Star/Java/death-star-2.java @@ -0,0 +1,125 @@ +import java.awt.Color; +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.List; + +import javax.imageio.ImageIO; + +public final class DeathStar { + + public static void main(String[] aArgs) throws IOException { + Vector direction = new Vector(20.0, -40.0, -10.0); + direction.normalise(); + Sphere positive = new Sphere(0, 0, 0, 120); + Sphere negative = new Sphere(-90, -90, -30, 100); + + BufferedImage image = deathStar(positive, negative, direction, 1.5, 0.5); + + ImageIO.write(image, "png", new File("DeathStarJava.png")); + } + + private static BufferedImage deathStar( + Sphere aPositive, Sphere aNegative, Vector aDirection, double aShadow, double aBrightness) { + final int width = aPositive.radius * 4; + final int height = aPositive.radius * 3; + BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); + Graphics graphics = result.getGraphics(); + graphics.setColor(Color.CYAN); + graphics.fillRect(0, 0, width, height); + + Vector ray = new Vector(0.0, 0.0, 0.0); + final int deltaX = aPositive.x - width / 2; + final int deltaY = aPositive.y - height / 2; + + double xMax = aPositive.x + aPositive.radius; + double yMax = aPositive.y + aPositive.radius; + for ( int y = aPositive.y - aPositive.radius; y < yMax; y++ ) { + for ( int x = aPositive.x - aPositive.radius; x < xMax; x++ ) { + List contacts = aPositive.contact(x, y); + final double zb1 = (double) contacts.get(0); + final int zb2 = (int) contacts.get(1); + final boolean positiveHit = (boolean) contacts.get(2); + if ( ! positiveHit ) { + continue; + } + contacts = aNegative.contact(x, y); + final double zs1 = (double) contacts.get(0); + final int zs2 = (int) contacts.get(1); + boolean negativeHit = (boolean) contacts.get(2); + if ( negativeHit ) { + if ( zs1 > zb1 ) { + negativeHit = false; + } else if ( zs2 > zb2 ) { + continue; + } + } + + if ( negativeHit ) { + ray.x = aNegative.x - x; + ray.y = aNegative.y - y; + ray.z = aNegative.z - zs2; + } else { + ray.x = x - aPositive.x; + ray.y = y - aPositive.y; + ray.z = zb1 - aPositive.z; + } + ray.normalise(); + double rayComponent = ray.scalarProduct(aDirection); + if ( rayComponent < 0 ) { + rayComponent = 0; + } + int color = (int) ( 255 * ( Math.pow(rayComponent, aShadow) + aBrightness) / ( 1 + aBrightness ) ); + if ( color < 0 ) { + color = 0; + } else if ( color > 255 ) { + color = 255; + } + result.setRGB(x - deltaX, y - deltaY, color); + } + } + return result; + } + + private static class Vector { + + public Vector(double aX, double aY, double aZ) { + x = aX; y = aY; z = aZ; + } + + public double scalarProduct(Vector aOther) { + return x * aOther.x + y * aOther.y + z * aOther.z; + } + + public Vector normalise() { + final double magnitude = Math.sqrt(this.scalarProduct(this)); + return new Vector(x /= magnitude, y /= magnitude, z /= magnitude); + } + + private double x, y, z; + + } + + private static class Sphere { + + public Sphere(int aX, int aY, int aZ, int aRadius) { + x = aX; y = aY; z = aZ; radius = aRadius; + } + + public List contact(int aX, int aY) { + final int xx = aX - x; + final int yy = aY - y; + final int zSquared = radius * radius - ( xx * xx + yy * yy ); + if ( zSquared >= 0 ) { + final double zz = Math.sqrt(zSquared); + return List.of(z - zz, z, true); + } + return List.of( 0.0, 0, false ); + } + + private int x, y, z, radius; + + } + +} diff --git a/Task/Deceptive-numbers/Java/deceptive-numbers.java b/Task/Deceptive-numbers/Java/deceptive-numbers.java new file mode 100644 index 0000000000..00d57a9110 --- /dev/null +++ b/Task/Deceptive-numbers/Java/deceptive-numbers.java @@ -0,0 +1,42 @@ +public final class DeceptiveNumbers { + + public static void main(String[] aArgs) { + int n = 7; + int count = 0; + while ( count < 100 ) { + if ( isDeceptive(n) ) { + System.out.print(String.format("%6d%s", n, ( ++count % 10 == 0 ? "\n" : " " ))); + } + n += 1; + } + } + + private static boolean isDeceptive(int aN) { + if ( aN % 2 != 0 && aN % 3 != 0 && aN % 5 != 0 && modulusPower(10, aN - 1, aN) == 1 ) { + for ( int divisor = 7; divisor < Math.sqrt(aN); divisor += 6 ) { + if ( aN % divisor == 0 || aN % ( divisor + 4 ) == 0 ) { + return true; + } + } + } + return false; + } + + private static long modulusPower(long aBase, long aExponent, long aModulus) { + if ( aModulus == 1 ) { + return 0; + } + + aBase %= aModulus; + long result = 1; + while ( aExponent > 0 ) { + if ( ( aExponent & 1 ) == 1 ) { + result = ( result * aBase ) % aModulus; + } + aBase = ( aBase * aBase ) % aModulus; + aExponent >>= 1; + } + return result; + } + +} diff --git a/Task/Deconvolution-1D/C++/deconvolution-1d.cpp b/Task/Deconvolution-1D/C++/deconvolution-1d.cpp new file mode 100644 index 0000000000..8047f5b2d0 --- /dev/null +++ b/Task/Deconvolution-1D/C++/deconvolution-1d.cpp @@ -0,0 +1,37 @@ +#include +#include +#include +#include + +void print_vector(const std::vector& list) { + std::cout << "["; + for ( uint64_t i = 0; i < list.size() - 1; ++i ) { + std::cout << list[i] << ", "; + } + std::cout << list.back() << "]" << std::endl; +} + +std::vector deconvolution(const std::vector& a, const std::vector& b) { + std::vector result(a.size() - b.size() + 1, 0); + for ( uint64_t n = 0; n < result.size(); n++ ) { + result[n] = a[n]; + uint64_t start = std::max((int) (n - b.size() + 1), 0); + for ( uint64_t i = start; i < n; i++ ) { + result[n] -= result[i] * b[n - i]; + } + result[n] /= b[0]; + } + return result; +} + +int main() { + const std::vector h = { -8, -9, -3, -1, -6, 7 }; + const std::vector f = { -3, -6, -1, 8, -6, 3, -1, -9, -9, 3, -2, 5, 2, -2, -7, -1 }; + const std::vector g = { 24, 75, 71, -34, 3, 22, -45, 23, 245, 25, 52, + 25, -67, -96, 96, 31, 55, 36, 29, -43, -7 }; + + std::cout << "h = "; print_vector(h); + std::cout << "deconvolution(g, f) = "; print_vector(deconvolution(g, f)); + std::cout << "f = "; print_vector(f); + std::cout << "deconvolution(g, h) = "; print_vector(deconvolution(g, h)); +} diff --git a/Task/Demings-funnel/C++/demings-funnel.cpp b/Task/Demings-funnel/C++/demings-funnel.cpp new file mode 100644 index 0000000000..8498ce3ff1 --- /dev/null +++ b/Task/Demings-funnel/C++/demings-funnel.cpp @@ -0,0 +1,76 @@ +#include +#include +#include +#include +#include +#include + +double mean(const std::vector& pseudo_random) { + double sum = 0.0; + for ( double item : pseudo_random ) { + sum += item; + } + return sum / pseudo_random.size(); +} + +double standard_deviation(const std::vector& pseudo_random) { + const double average = mean(pseudo_random); + double sum_squares = 0.0; + for ( double item : pseudo_random ) { + sum_squares += item * item; + } + return sqrt(sum_squares / pseudo_random.size() - average * average); +} + +std::vector funnel(const std::vector& pseudo_random, + const std::function& rule) { + double value = 0.0; + std::vector result(pseudo_random.size(), 0); + + for ( size_t i = 0; i < pseudo_random.size(); i++ ) { + const double result_value = value + pseudo_random[i]; + value = rule(value, pseudo_random[i]); + result[i] = result_value; + } + return result; +} + +void experiment(const std::string& label, const std::vector& pseudo_random_xs, + const std::vector& pseudo_random_ys, const std::function& rule) { + + std::vector result_x = funnel(pseudo_random_xs, rule); + std::vector result_y = funnel(pseudo_random_ys, rule); + + std::cout << label << std::endl; + std::cout << "-----------------------------------------" << std::endl; + std::cout << "Mean x, y" << std::setw(16) << ": " << std::fixed << std::setprecision(4) + << mean(result_x) << ", " << mean(result_y) << std::endl; + std::cout << "Standard deviation x, y: " << standard_deviation(result_x) << ", " + << standard_deviation(result_y) << std::endl; + std::cout << std::endl; +} + +int main() { + const std::vector pseudo_random_xs = { -0.533, 0.270, 0.859, -0.043, -0.205, -0.127, -0.071, + 0.275, 1.251, -0.231, -0.401, 0.269, 0.491, 0.951, 1.150, 0.001, -0.382, 0.161, 0.915, 2.080, -2.337, + 0.034, -0.126, 0.014, 0.709, 0.129, -1.093, -0.483, -1.193, 0.020, -0.051, 0.047, -0.095, 0.695, 0.340, + -0.182, 0.287, 0.213, -0.423, -0.021, -0.134, 1.798, 0.021, -1.099, -0.361, 1.636, -1.134, 1.315, + 0.201, 0.034, 0.097, -0.170, 0.054, -0.553, -0.024, -0.181, -0.700, -0.361, -0.789, 0.279, -0.174, + -0.009, -0.323, -0.658, 0.348, -0.528, 0.881, 0.021, -0.853, 0.157, 0.648, 1.774, -1.043, 0.051, + 0.021, 0.247, -0.310, 0.171, 0.000, 0.106, 0.024, -0.386, 0.962, 0.765, -0.125, -0.289, 0.521, + 0.017, 0.281, -0.749, -0.149, -2.436, -0.909, 0.394, -0.113, -0.598, 0.443, -0.521, -0.799, 0.087 }; + + const std::vector pseudo_random_ys = { 0.136, 0.717, 0.459, -0.225, 1.392, 0.385, 0.121, -0.395, + 0.490, -0.682, -0.065, 0.242, -0.288, 0.658, 0.459, 0.000, 0.426, 0.205, -0.765, -2.188, -0.742, + -0.010, 0.089, 0.208, 0.585, 0.633, -0.444, -0.351, -1.087, 0.199, 0.701, 0.096, -0.025, -0.868, 1.051, + 0.157, 0.216, 0.162, 0.249, -0.007, 0.009, 0.508, -0.790, 0.723, 0.881, -0.508, 0.393, -0.226, 0.710, + 0.038, -0.217, 0.831, 0.480, 0.407, 0.447, -0.295, 1.126, 0.380, 0.549, -0.445, -0.046, 0.428, -0.074, + 0.217, -0.822, 0.491, 1.347, -0.141, 1.230, -0.044, 0.079, 0.219, 0.698, 0.275, 0.056, 0.031, 0.421, 0.064, + 0.721, 0.104, -0.729, 0.650, -1.103, 0.154, -1.720, 0.051, -0.385, 0.477, 1.537, -0.901, 0.939, -0.411, + 0.341, -0.411, 0.106, 0.224, -0.947, -1.424, -0.542, -1.032 }; + + experiment("Rule 1:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return 0.0; }); + experiment("Rule 2:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -dz; }); + experiment("Rule 3:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return -( z + dz ); }); + experiment("Rule 4:", pseudo_random_xs, pseudo_random_ys, [](double z, double dz) -> double { return z + dz; }); +} diff --git a/Task/Descending-primes/Java/descending-primes.java b/Task/Descending-primes/Java/descending-primes.java new file mode 100644 index 0000000000..44fe8d0b6b --- /dev/null +++ b/Task/Descending-primes/Java/descending-primes.java @@ -0,0 +1,48 @@ +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +public final class DescendingPrimes { + + public static void main(String[] aArgs) { + List allNumbersStrictlyDescendingDigits = new ArrayList(512); + for ( int i = 0; i < 512; i++ ) { + int number = 0; + int temp = i; + int digit = 9; + while ( temp > 0 ) { + if ( temp % 2 == 1 ) { + number = number * 10 + digit; + } + temp >>= 1; + digit -= 1; + } + allNumbersStrictlyDescendingDigits.add(number); + } + + Collections.sort(allNumbersStrictlyDescendingDigits); + + int count = 0; + for ( int number : allNumbersStrictlyDescendingDigits ) { + if ( isPrime(number) ) { + System.out.print(String.format("%9d%s", number, ( ++count % 10 == 0 ? "\n" : " " ))); + } + } + System.out.println(System.lineSeparator()); + System.out.println("There are " + count + " descending primes."); + } + + private static boolean isPrime(int aNumber) { + if ( aNumber < 2 || ( aNumber % 2 ) == 0 ) { + return aNumber == 2; + } + + for ( int divisor = 3; divisor * divisor <= aNumber; divisor += 2 ) { + if ( aNumber % divisor == 0 ) { + return false; + } + } + return true; + } + +} diff --git a/Task/Determine-if-two-triangles-overlap/ATS/determine-if-two-triangles-overlap.ats b/Task/Determine-if-two-triangles-overlap/ATS/determine-if-two-triangles-overlap.ats new file mode 100644 index 0000000000..d4116b822f --- /dev/null +++ b/Task/Determine-if-two-triangles-overlap/ATS/determine-if-two-triangles-overlap.ats @@ -0,0 +1,341 @@ +(* Given that the context is collision detection, we will consider + containment of one triangle entirely inside the other as ‘overlap’ + and test for that, as well as for overlap of the triangle sides + themselves. One must agree that, if one triangle has become buried + entirely inside another, then the two have collided. There are + consequences for the conservation of momentum. + + Besides, the full set of overlap tests, INCLUDING containment of + one polygonal hull inside another, is relevant to the problem of + finding intersections of Bézier curves. See + https://rosettacode.org/wiki/B%C3%A9zier_curves/Intersections + + This code specifically tests for overlapping vertices, in case the + main tests fail to catch such overlaps. Approximate equality is + employed rather than exact floating-point equality. *) + +#include "share/atspre_staload.hats" + +%{^ +#include +#include +%} + +macdef dbl_epsilon = $extval (double, "DBL_EPSILON") + +(* We will use some simple homogeneous geometric algebra. *) + +typedef point = + @{e1 = double, + e2 = double, + e0 = double} + +macdef Pt (x, y) = (* Shorthand for creating a normalized point. *) + @{e1 = ,(x), + e2 = ,(y), + e0 = 1.0} : point + +typedef line = + @{e0_e1 = double, + e0_e2 = double, + e1_e2 = double} + +typedef triangle = @(point, point, point) + +fn +outer_product_point_point (a : point, b : point) : line = + @{e0_e1 = ~(~a.e0 * b.e1 + a.e1 * b.e0), + e0_e2 = ~(~a.e0 * b.e2 + a.e2 * b.e0), + e1_e2 = (a.e1 * b.e2 - a.e2 * b.e1)} + +fn +left_contraction_point_line (a : point, b : line) : point = + @{e1 = (a.e0 * b.e0_e1 - a.e2 * b.e1_e2), + e2 = (a.e0 * b.e0_e2 + a.e1 * b.e1_e2), + e0 = (~a.e1 * b.e0_e1 - a.e2 * b.e0_e2)} + +fn +left_contraction_point_point (a : point, b : point) : double = + (* This is the same as the scalar product but saves us having to add + an operator for which I cannot think of a good symbol. *) + (a.e1 * b.e1) + (a.e2 * b.e2) + (a.e0 * b.e0) + +fn +dual_line (a : line) : point = + @{e1 = ~a.e0_e2, + e2 = a.e0_e1, + e0 = a.e1_e2} + +overload outer_product with outer_product_point_point +overload left_contraction with left_contraction_point_line +overload left_contraction with left_contraction_point_point +overload dual with dual_line (* Orthogonal complement. *) +infixl ( * ) ^ .| +overload ^ with outer_product +overload .| with left_contraction + +fn +intersection_line_line (a : line, b : line) : point = + let + val p = dual a .| b + in + if p.e0 = 0.0 then + (* The lines are parallel (or coincident, if p is all zeros). *) + p + else + (* Normalize the intersection point. *) + @{e1 = p.e1 / p.e0, + e2 = p.e2 / p.e0, + e0 = 1.0} + end + +fn +which_side_point_line (a : point, b : line) : Sgn = + (* 1 = left, 0 = lies on the line, ~1 = right *) + let + val x = dual b .| a + in + if x < 0.0 then + ~1 + else if x > 0.0 then + 1 + else + 0 + end + +overload intersection with intersection_line_line +overload which_side with which_side_point_line + +fn +orientation_triangle (t : triangle) : Sgn = + (* 1 = counterclockwise, 0 = collinear, ~1 = clockwise *) + which_side (t.2, t.0 ^ t.1) + +overload orientation with orientation_triangle + +fn +set_orientation_triangle {s : int | abs s == 1} + (t : triangle, s : int s) : triangle = + (* 1 = counterclockwise, ~1 = clockwise. If the triangle is + collinear, leave it unchanged. If the triangle does need + rearrangement, do so by swapping vertices t.1 and t.2. *) + let + val s0 = orientation t + in + if (s = 0) + (s = s0) then + t + else + @(t.0, t.2, t.1) + end + +overload set_orientation with set_orientation_triangle + +fn +overlap_triangle_triangle (t1 : triangle, t2 : triangle) : bool = + let + val t1 = set_orientation (t1, 1) + and t2 = set_orientation (t2, 1) + + (* The lines that form the sides of the triangles. *) + val s1 = @(t1.0 ^ t1.1, t1.1 ^ t1.2, t1.2 ^ t1.0) + val s2 = @(t2.0 ^ t2.1, t2.1 ^ t2.2, t2.2 ^ t2.0) + + fn + sides_intersect (pa : point, pb : point, ln_p : line, + qa : point, qb : point, ln_q : line) : bool = + let + val x = intersection (ln_p, ln_q) + in + if x.e0 <> 0.0 then + let + val px_min = min (pa.e1, pb.e1) + and px_max = max (pa.e1, pb.e1) + and py_min = min (pa.e2, pb.e1) + and py_max = max (pa.e2, pb.e1) + + val px_min2 = px_min + px_min + and px_max2 = px_max + px_max + and py_min2 = py_min + py_min + and py_max2 = py_max + py_max + + val px_min_eps = abs (px_min) * dbl_epsilon + and px_max_eps = abs (px_max) * dbl_epsilon + val py_min_eps = abs (py_min) * dbl_epsilon + and py_max_eps = abs (py_max) * dbl_epsilon + in + if px_min2 - px_min_eps <= x.e1 + x.e1 + && x.e1 + x.e1 <= px_max2 + px_max_eps + && py_min2 - py_min_eps <= x.e2 + x.e2 + && x.e2 + x.e2 <= py_max2 + py_max_eps then + let + val qx_min = min (qa.e1, qb.e1) + and qx_max = max (qa.e1, qb.e1) + and qy_min = min (qa.e2, qb.e1) + and qy_max = max (qa.e2, qb.e1) + + val qx_min2 = qx_min + qx_min + and qx_max2 = qx_max + qx_max + and qy_min2 = qy_min + qy_min + and qy_max2 = qy_max + qy_max + + val qx_min_eps = abs (qx_min) * dbl_epsilon + and qx_max_eps = abs (qx_max) * dbl_epsilon + val qy_min_eps = abs (qy_min) * dbl_epsilon + and qy_max_eps = abs (qy_max) * dbl_epsilon + in + qx_min2 - qx_min_eps <= x.e1 + x.e1 + && x.e1 + x.e1 <= qx_max2 + qx_max_eps + && qy_min2 - qy_min_eps <= x.e2 + x.e2 + && x.e2 + x.e2 <= qy_max2 + qy_max_eps + end + else + false + end + else if x.e1 = 0.0 && x.e2 = 0.0 then + (* The lines are coincident *) + ~(max (qa.e1, qb.e1) < min (pa.e1, pb.e1) + || max (pa.e1, pb.e1) < min (qa.e1, qb.e1)) + && ~(max (qa.e2, qb.e2) < min (pa.e2, pb.e2) + || max (pa.e2, pb.e2) < min (qa.e2, qb.e2)) + else + (* The lines are parallel. *) + false + end + + fn + sides_intersection_tests () : bool = + sides_intersect (t1.0, t1.1, s1.0, t2.0, t2.1, s2.0) + || sides_intersect (t1.0, t1.1, s1.0, t2.1, t2.2, s2.1) + || sides_intersect (t1.0, t1.1, s1.0, t2.2, t2.0, s2.2) + || sides_intersect (t1.1, t1.2, s1.1, t2.0, t2.1, s2.0) + || sides_intersect (t1.1, t1.2, s1.1, t2.1, t2.2, s2.1) + || sides_intersect (t1.1, t1.2, s1.1, t2.2, t2.0, s2.2) + || sides_intersect (t1.2, t1.0, s1.2, t2.0, t2.1, s2.0) + || sides_intersect (t1.2, t1.0, s1.2, t2.1, t2.2, s2.1) + || sides_intersect (t1.2, t1.0, s1.2, t2.2, t2.0, s2.2) + + fn + points_approx_equal (p : point, q : point) : bool = + let + val @{e1 = px, e2 = py, e0 = _} = p + and @{e1 = qx, e2 = qy, e0 = _} = q + + val x_max_eps = max (abs px, abs qx) * dbl_epsilon + and y_max_eps = max (abs py, abs py) * dbl_epsilon + in + abs ((px + px) - (qx + qx)) <= x_max_eps + && abs ((py + py) - (qy + qy)) <= y_max_eps + end + + fn + vertex_vertex_tests () : bool = + points_approx_equal (t1.0, t2.0) + || points_approx_equal (t1.0, t2.1) + || points_approx_equal (t1.0, t2.2) + || points_approx_equal (t1.1, t2.0) + || points_approx_equal (t1.1, t2.1) + || points_approx_equal (t1.1, t2.2) + || points_approx_equal (t1.2, t2.0) + || points_approx_equal (t1.2, t2.1) + || points_approx_equal (t1.2, t2.2) + + fn + is_inside (a : point, b : @(line, line, line)) : bool = + which_side (a, b.0) = 1 + && which_side (a, b.1) = 1 + && which_side (a, b.2) = 1 + + fn + vertex_insideness_tests () : bool = + is_inside (t1.0, s2) + || is_inside (t1.1, s2) + || is_inside (t1.2, s2) + || is_inside (t2.0, s1) + || is_inside (t2.1, s1) + || is_inside (t2.2, s1) + in + sides_intersection_tests () + || vertex_vertex_tests () + || vertex_insideness_tests () + end + +overload overlap with overlap_triangle_triangle + +fn +println_triangle (t : triangle) : void = + println! ("(", t.0.e1, ",", t.0.e2, ")--(", + t.1.e1, ",", t.1.e2, ")--(", + t.2.e1, ",", t.2.e2, ")--cycle") + +fn +test_triangles (t1 : triangle, t2 : triangle) : void = + begin + println_triangle t1; + println_triangle t2; + println! (" overlap: ", overlap (t1, t2)) + end + +implement +main () = + begin + println! (); + test_triangles (@(Pt (0.0, 0.0), + Pt (5.0, 0.0), + Pt (0.0, 5.0)), + @(Pt (0.0, 0.0), + Pt (5.0, 0.0), + Pt (0.0, 6.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (0.0, 5.0), + Pt (5.0, 0.0)), + @(Pt (0.0, 0.0), + Pt (0.0, 5.0), + Pt (5.0, 0.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (5.0, 0.0), + Pt (0.0, 5.0)), + @(Pt (~10.0, 0.0), + Pt ( ~5.0, 0.0), + Pt ( ~1.0, 6.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (5.0, 0.0), + Pt (2.5, 5.0)), + @(Pt (0.0, 4.0), + Pt (2.5, ~1.0), + Pt (5.0, 4.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (1.0, 1.0), + Pt (0.0, 2.0)), + @(Pt (2.0, 1.0), + Pt (3.0, 0.0), + Pt (3.0, 2.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (1.0, 1.0), + Pt (0.0, 2.0)), + @(Pt (2.0, 1.0), + Pt (3.0, ~2.0), + Pt (3.0, 4.0))); + test_triangles (@(Pt (0.0, 0.0), + Pt (1.0, 0.0), + Pt (0.0, 1.0)), + @(Pt (1.0, 0.0), + Pt (2.0, 0.0), + Pt (1.0, 1.0))); + + println! (); + println! ("What follows is a test where one triangle is ", + "contained entirely"); + println! ("inside the other. Without such a test, our ", + "algorithm would have"); + println! ("one of its features undemonstrated."); + println! (); + test_triangles (@(Pt ( 0.0, 0.0), + Pt (10.0, 0.0), + Pt ( 5.0, 10.0)), + @(Pt ( 4.0, 1.0), + Pt ( 5.0, 2.0), + Pt ( 6.0, 1.0))); + println! (); + + 0 + end diff --git a/Task/Determine-if-two-triangles-overlap/OoRexx/determine-if-two-triangles-overlap.rexx b/Task/Determine-if-two-triangles-overlap/OoRexx/determine-if-two-triangles-overlap.rexx index 750266d9d0..f78c10af8a 100644 --- a/Task/Determine-if-two-triangles-overlap/OoRexx/determine-if-two-triangles-overlap.rexx +++ b/Task/Determine-if-two-triangles-overlap/OoRexx/determine-if-two-triangles-overlap.rexx @@ -3,9 +3,9 @@ * Fully (?) tested with integer coordinates of the 6 corners * This was/is an exercise with ooRexx * Removed the fraction arithmetic +* add test for triangles' validity *-------------------------------------------------------------------*/ Parse Version v - oid='trioo.txt'; 'erase' oid Call o v case=0 @@ -21,6 +21,8 @@ Call trio_test '0 0 5 0 2.5 5 0 4 2.5 -1 5 4' Call trio_test '0 0 1 1 0 2 2 1 3 0 3 2' Call trio_test '0 0 1 1 0 2 2 1 3 -2 3 4' Call trio_test '0 0 1 0 0 1 1 0 2 0 1 1' +Call trio_test '0 0 0 0 2 2 1 1 2 1 1 2' -- two points are identical +Call trio_test '0 0 0 3 2 2 1 1 2 2 3 3' -- three points on a line Exit /* Other test cases */ Call trio_test '0 0 0 4 4 0 0 2 2 2 2 0' @@ -54,6 +56,7 @@ Parse Arg tlist cc+=1 tlist=space(tlist) tl1=tlist ; Call trio_t tl1 +If result=-1 Then Return tl2=reversex(tlist) ; Call trio_t tl2 tl3='' tl=tlist @@ -64,13 +67,19 @@ Do While tl<>'' Call trio_t tl3 tl4=reversex(tl3) ; Call trio_t tl4 tl5=subword(tl4,7) subword(tl4,1,6) ; Call trio_t tl5 -tl6=subword(tl5,7) subword(tl5,1,6) ; Call trio_t tl6 +tl6='' +tl=tlist +Do While tl<>'' + Parse Var tl x y tl + tl6=tl6 y x + End + Call trio_t tl6 Return trio_t: Parse Arg tlist tlist=space(tlist) -Say tlist +Say '>' tlist case+=1 Parse Arg ax ay bx by cx cy dx dy ex ey fx fy /*--------------------------------------------------------------------- @@ -78,6 +87,14 @@ Parse Arg ax ay bx by cx cy dx dy ex ey fx fy *--------------------------------------------------------------------*/ a=.point~new(ax,ay); b=.point~new(bx,by); c=.point~new(cx,cy) d=.point~new(dx,dy); e=.point~new(ex,ey); f=.point~new(fx,fy) +If area(a,b,c)=0 Then Do + Say a b c 'is not a valid triangle' + Return -1 + End +If area(d,e,f)=0 Then Do + Say d e f 'is not a valid triangle' + Return -1 + End abc=.triangle~new(a,b,c) def=.triangle~new(d,e,f) Call o 'Triangle: ABC:' abc ,1 @@ -282,6 +299,10 @@ Return ::method init expose point edge use arg p1,p2,p3 + If area(p1,p2,p3)=0 Then Do + Say p1 p2 p3 'is not a valid triangle!' + Return .nil + End point=.array~new point[1]=p1 point[2]=p2 @@ -545,3 +566,26 @@ Return res=res word(list,i) End Return res + +::ROUTINE distpp PUBLIC --Compute the distance between the points A and B +/*********************************************************************** +* Compute the distance between the points A and B +***********************************************************************/ + Use Arg A,B + ax=A~x; ay=A~y; bx=B~x; by=B~y + res=rxCalcsqrt((bx-ax)**2+(by-ay)**2) + Return res + +::ROUTINE area PUBLIC --Compute the area of the triangla A B C +/*********************************************************************** +* Compute the area of the triangla A B C +***********************************************************************/ + Use Arg A,B,C + ax=A~x; ay=A~y; bx=B~x; by=B~y; cx=C~x; cy=C~y + ab=distpp(A,B) + bc=distpp(B,C) + ca=distpp(C,A) + s=(ab+bc+ca)/2 + area=rxCalcsqrt(s*(s-ab)*(s-bc)*(s-ca)) + Return area +::REQUIRES rxMath Library diff --git a/Task/Determine-sentence-type/C++/determine-sentence-type.cpp b/Task/Determine-sentence-type/C++/determine-sentence-type.cpp new file mode 100644 index 0000000000..28fa3dcf40 --- /dev/null +++ b/Task/Determine-sentence-type/C++/determine-sentence-type.cpp @@ -0,0 +1,31 @@ +#include +#include +#include +#include + +char sentence_type(const std::string& sentence) { + if ( sentence.empty() ) { + throw std::invalid_argument("Cannot classify an empty sentence"); + } + + char result; + const char last_character = sentence.back(); + switch (last_character) { + case '?': result = 'Q'; break; + case '.': result = 'S'; break; + case '!': result = 'E'; break; + default: result = 'N'; break; + }; + return result; +} + +int main() { + const std::vector sentences = { "hi there, how are you today?", + "I'd like to present to you the washing machine 9001.", + "You have been nominated to win one of these!", + "Just make sure you don't break it" }; + + for ( const std::string& sentence : sentences ) { + std::cout << sentence << " -> " << sentence_type(sentence) << std::endl; + } +} diff --git a/Task/Determine-sentence-type/Java/determine-sentence-type.java b/Task/Determine-sentence-type/Java/determine-sentence-type.java new file mode 100644 index 0000000000..bcc205e963 --- /dev/null +++ b/Task/Determine-sentence-type/Java/determine-sentence-type.java @@ -0,0 +1,30 @@ +import java.util.List; + +public final class DetermineSentenceType { + + public static void main(String[] aArgs) { + List sentences = List.of( "hi there, how are you today?", + "I'd like to present to you the washing machine 9001.", + "You have been nominated to win one of these!", + "Just make sure you don't break it" ); + + for ( String sentence : sentences ) { + System.out.println(sentence + " -> " + sentenceType(sentence)); + } + } + + private static char sentenceType(String aSentence) { + if ( aSentence.isEmpty() ) { + throw new IllegalArgumentException("Cannot classify an empty sentence"); + } + + final char lastCharacter = aSentence.charAt(aSentence.length() - 1); + return switch (lastCharacter) { + case '?' -> 'Q'; + case '.' -> 'S'; + case '!' -> 'E'; + default -> 'N'; + }; + } + +} diff --git a/Task/Dice-game-probabilities/Sidef/dice-game-probabilities.sidef b/Task/Dice-game-probabilities/Sidef/dice-game-probabilities.sidef index 59f888cbcb..1065807331 100644 --- a/Task/Dice-game-probabilities/Sidef/dice-game-probabilities.sidef +++ b/Task/Dice-game-probabilities/Sidef/dice-game-probabilities.sidef @@ -11,9 +11,9 @@ func winning(sides1, n1, sides2, n2) { var (p1, p2) = (combos(sides1, n1), combos(sides2, n2)) var (win,loss,tie) = (0,0,0) p1.each_kv { |i, x| - win += x*p2.ft(0,i-1).sum - tie += x*p2.ft(i, i).sum - loss += x*p2.ft(i+1).sum + win += x*p2.first(i).sum + tie += x*p2.slice(i).first(1).sum + loss += x*p2.slice(i+1).sum } [win, tie, loss] »/» p1.sum*p2.sum } diff --git a/Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust b/Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust new file mode 100644 index 0000000000..5c5d526d93 --- /dev/null +++ b/Task/Dinesmans-multiple-dwelling-problem/Rust/dinesmans-multiple-dwelling-problem.rust @@ -0,0 +1,18 @@ +use itertools::Itertools; + + +fn main() { + for p in (1..6).permutations(5) { + let baker: i32 = p[0]; + let cooper: i32 = p[1]; + let fletcher: i32 = p[2]; + let miller: i32 = p[3]; + let smith: i32 = p[4]; + if baker != 5 && cooper != 1 && fletcher != 1 && fletcher != 5 && cooper < miller && + (smith - fletcher).abs() > 1 && (cooper - fletcher).abs() > 1 { + print!("Baker on {baker}, Cooper on {cooper}, "); + println!("Fletcher on {fletcher}, Miller on {miller}, Smith on {smith}."); + break; + } + } +} diff --git a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef index e17edbb94c..bca86e7d61 100644 --- a/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef +++ b/Task/Dinesmans-multiple-dwelling-problem/Sidef/dinesmans-multiple-dwelling-problem-1.sidef @@ -9,7 +9,7 @@ func dinesman(problem) { var re_keywords = Regex(words.join('|'))   # Build an array of lambda's - var predicates = lines.ft(1, lines.end-1).map{ |line| + var predicates = lines.first(-1).last(-1).map{ |line| var keywords = line.scan(re_keywords) var (name1, name2) = line.scan(re_names)...   diff --git a/Task/Distance-and-Bearing/C++/distance-and-bearing.cpp b/Task/Distance-and-Bearing/C++/distance-and-bearing.cpp new file mode 100644 index 0000000000..1ca64a570a --- /dev/null +++ b/Task/Distance-and-Bearing/C++/distance-and-bearing.cpp @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +constexpr double RADIUS = 6'371 / 1.852; // Mean radius of the Earth in nautical miles +constexpr double RADIAN_TO_DEGREE = 180.0 / std::numbers::pi; + +class airport { +public: + airport(std::string aName, std::string aCountry, std::string aIcao, double aLatitude, double aLongitude) + : name(aName), country(aCountry), icao(aIcao), latitude(aLatitude), longitude(aLongitude) {} + + std::string name; + std::string country; + std::string icao; + double latitude; + double longitude; +}; + +// Convert the given string to a double, which represents an angle, +// and then convert the angle from degrees to radians +double to_double_radians(const std::string& text) { + std::istringstream stream(text); + double decimal = 0.0; + stream >> decimal; + return decimal / RADIAN_TO_DEGREE; +} + +std::string do_replace(const std::string& text, const std::string& original, const std::string& replacement) { + return std::regex_replace(text, std::regex(original), replacement); +} + +std::vector split(const std::string& line, const char& delimiter) { + std::stringstream stream(line); + std::string item; + std::vector items; + while ( std::getline(stream, item, delimiter) ) { + items.push_back(std::move(item)); + } + return items; +} + +void read_file(const std::string& file_name, std::vector& airports) { + std::ifstream airports_file(file_name); + std::string line; + while ( std::getline(airports_file, line) ) { + std::vector sections = split(line, ','); + airport air_port(do_replace(sections[1], "\"", ""), // Remove the double quotes from the string + do_replace(sections[3], "\"", ""), + do_replace(sections[5], "\"", ""), + to_double_radians(sections[6]), + to_double_radians(sections[7])); + airports.push_back(std::move(air_port)); + } + airports_file.close(); +} + +// The given angles are in radians, and the result is in nautical miles. +double distance(double phi1, double lambda1, double phi2, double lambda2) { + double a = pow(sin((phi2 - phi1) * 0.5), 2) + cos(phi1) * cos(phi2) * pow(sin((lambda2 - lambda1) * 0.5), 2); + double c = 2 * atan2(sqrt(a), sqrt(1 - a)); + return RADIUS * c; +} + +// The given angles are in radians, and the result is in degrees in the range [0, 360). +double bearing(double phi1, double lambda1, double phi2, double lambda2) { + double delta = lambda2 - lambda1; + double result = atan2(sin(delta) * cos(phi2), cos(phi1) * sin(phi2) - sin(phi1) * cos(phi2) * cos(delta)); + return std::fmod(result * RADIAN_TO_DEGREE + 360.0, 360.0); +} + +int main() { + std::vector airports; + read_file("airports.dat", airports); + + const double plane_latitude = 51.514669 / RADIAN_TO_DEGREE; + const double plane_longitude = 2.198581 / RADIAN_TO_DEGREE; + + std::vector> distances; + for ( uint64_t i = 0; i < airports.size(); ++i ) { + double dist = distance(plane_latitude, plane_longitude, airports[i].latitude, airports[i].longitude); + distances.push_back(std::make_pair(dist, i)); + } + + std::sort(distances.begin(), distances.end(), + [](auto& left, auto& right) { return left.first < right.first; }); + + std::cout << "Distance" << std::setw(9) << "Bearing" << std::setw(11) << "ICAO" + << std::setw(20) << "Country" << std::setw(40) << "Airport" << std::endl; + std::cout << std::string(88, '-') << std::endl; + + for ( uint32_t i = 0; i < 20; ++i ) { + auto[distance, index] = distances[i]; + airport air_port = airports[index]; + double bear = bearing(plane_latitude, plane_longitude, air_port.latitude, air_port.longitude); + + std::cout << std::setw(8) << std::fixed << std::setprecision(1) << distance + << std::setw(9) << std::setprecision(0) << std::round(bear) + << std::setw(11) << air_port.icao << std::setw(20) << air_port.country + << std::setw(40) << air_port.name << std::endl; + } +} diff --git a/Task/Duffinian-numbers/Java/duffinian-numbers.java b/Task/Duffinian-numbers/Java/duffinian-numbers.java new file mode 100644 index 0000000000..47f094d86a --- /dev/null +++ b/Task/Duffinian-numbers/Java/duffinian-numbers.java @@ -0,0 +1,61 @@ +import java.util.Arrays; + +public final class DuffianNumbers { + + public static void main(String[] aArgs) { + int[] duffians = createDuffians(11_000); + + System.out.println("The first 50 Duffinian numbers:"); + int count = 0; + int n = 1; + while ( count < 50 ) { + if ( duffians[n] > 0 ) { + System.out.print(String.format("%4d%s", n, ( ++count % 25 == 0 ? "\n" : "" ))); + } + n += 1; + } + System.out.println(); + + System.out.println("The first 16 Duffinian triplets:"); + count = 0; + n = 3; + while( count < 16 ) { + if ( duffians[n - 2] > 0 && duffians[n - 1] > 0 && duffians[n] > 0 ) { + System.out.print(String.format("%22s%s", + "(" + ( n - 2 ) + ", " + ( n - 1 ) + ", " + n + ")", ( ++count % 4 == 0 ? "\n" : "" ))); + } + n += 1; + } + System.out.println(); + } + + private static int[] createDuffians(int aLimit) { + // Create a list where list[i] is the divisor sum of i. + int[] result = new int[aLimit]; + Arrays.fill(result, 1); + for ( int i = 2; i < aLimit; i++ ) { + for ( int j = i; j < aLimit; j += i ) { + result[j] += i; + } + } + + // Set the divisor sum of non-Duffinian numbers to 0. + result[1] = 0; // 1 is not a Duffinian number. + for ( int n = 2; n < aLimit; n++ ) { + int resultN = result[n]; + if ( resultN == n + 1 || gcd(n, resultN) != 1 ) { + // n is prime, or it is not relatively prime to its divisor sum. + result[n] = 0; + } + } + return result; + } + + private static int gcd(int aOne, int aTwo) { + if ( aTwo == 0 ) { + return aOne; + } + return gcd(aTwo, aOne % aTwo); + } + +} diff --git a/Task/EKG-sequence-convergence/C++/ekg-sequence-convergence.cpp b/Task/EKG-sequence-convergence/C++/ekg-sequence-convergence.cpp new file mode 100644 index 0000000000..09597f1d6e --- /dev/null +++ b/Task/EKG-sequence-convergence/C++/ekg-sequence-convergence.cpp @@ -0,0 +1,59 @@ +#include +#include +#include +#include +#include +#include + +void print_vector(const std::vector& list) { + std::cout << "["; + for ( uint64_t i = 0; i < list.size() - 1; ++i ) { + std::cout << list[i] << ", "; + } + std::cout << list.back() << "]" << std::endl; +} + +bool contains(const std::vector& list, const int32_t& n) { + return std::find(list.begin(), list.end(), n) != list.end(); +} + +bool same_sequence(const std::vector& seq1, const std::vector& seq2, const int32_t& n) { + for ( uint64_t i = n ; i < seq1.size() ; ++i ) { + if ( seq1[i] != seq2[i] ) { + return false; + } + } + return true; +} + +std::vector ekg(const int32_t& second_term, const uint64_t& term_count) { + std::vector result = { 1, second_term }; + int32_t candidate = 2; + while ( result.size() < term_count ) { + if ( ! contains(result, candidate) && std::gcd(result.back(), candidate) > 1 ) { + result.push_back(candidate); + candidate = 2; + } else { + candidate++; + } + } + return result; +} + +int main() { + std::cout << "The first 10 members of EKG[2], EKG[5], EKG[7], EKG[9] and EKG[10] are:" << std::endl; + for ( int32_t i : { 2, 5, 7, 9, 10 } ) { + std::cout << "EKG[" << std::setw(2) << i << "] = "; print_vector(ekg(i, 10)); + } + std::cout << std::endl; + + std::vector ekg5 = ekg(5, 100); + std::vector ekg7 = ekg(7, 100); + int32_t i = 1; + while ( ! ( ekg5[i] == ekg7[i] && same_sequence(ekg5, ekg7, i) ) ) { + i++; + } + // Converting from 0-based to 1-based index + std::cout << "EKG[5] and EKG[7] converge at index " << i + 1 + << " with a common value of " << ekg5[i] << "." << std::endl; +} diff --git a/Task/Enumerations/EMal/enumerations.emal b/Task/Enumerations/EMal/enumerations.emal new file mode 100644 index 0000000000..60c6220bd6 --- /dev/null +++ b/Task/Enumerations/EMal/enumerations.emal @@ -0,0 +1,22 @@ +in Org:RosettaCode +type Fruits +enum + int APPLE, BANANA, CHERRY +end +type ExplicitFruits +enum + int APPLE = 10 + int BANANA = 20 + int CHERRY = 1 +end +type Main +for each generic enumeration in generic[Fruits, ExplicitFruits] + writeLine("[" + Generic.name(enumeration) + "]") + writeLine("getting an object with value = 1:") + writeLine(:enumeration.byValue(1)) + writeLine("iterating over the items:") + for each var fruit in :enumeration + writeLine(fruit) + end + writeLine() +end diff --git a/Task/Executable-library/Sidef/executable-library-1.sidef b/Task/Executable-library/Sidef/executable-library-1.sidef index 9fc471fa73..0c21e726d0 100644 --- a/Task/Executable-library/Sidef/executable-library-1.sidef +++ b/Task/Executable-library/Sidef/executable-library-1.sidef @@ -2,16 +2,16 @@ func hailstone(n) { gather { while (n > 1) { take(n) - n = (n.is_even ? n/2 : (3*n + 1)) + n = (n.is_even ? (n/2) : (take(3*n + 1)/2)) } take(1) } } -  + if (__FILE__ == __MAIN__) { # true when not imported var seq = hailstone(27) - say "hailstone(27) - #{seq.len} elements: #{seq.ft(0, 3)} [...] #{seq.ft(-4)}" -  + say "hailstone(27) - #{seq.len} elements: #{seq.first(4)} [...] #{seq.last(4)}" + var n = 0 var max = 0 100_000.times { |i| @@ -21,6 +21,6 @@ if (__FILE__ == __MAIN__) { # true when not imported n = i } } -  + say "Longest sequence is for #{n}: #{max}" } diff --git a/Task/FASTA-format/ALGOL-68/fasta-format.alg b/Task/FASTA-format/ALGOL-68/fasta-format.alg new file mode 100644 index 0000000000..0af6a2dd55 --- /dev/null +++ b/Task/FASTA-format/ALGOL-68/fasta-format.alg @@ -0,0 +1,22 @@ +BEGIN # read FASTA format data from standard input and write the results to # + # standard output - only the ">" line start is handled # + + BOOL at eof := FALSE; + on logical file end( stand in, ( REF FILE f )BOOL: at eof := TRUE ); + + WHILE STRING line; + read( ( line, newline ) ); + NOT at eof + DO + IF line /= "" THEN # non-empty line # + INT start := LWB line; + BOOL is heading = line[ start ] = ">"; # check for heading line # + IF is heading THEN + print( ( newline ) ); + start +:= 1 + FI; + print( ( line[ start : ] ) ); + IF is heading THEN print( ( ": " ) ) FI + FI + OD +END diff --git a/Task/FASTA-format/PL-M/fasta-format.plm b/Task/FASTA-format/PL-M/fasta-format.plm new file mode 100644 index 0000000000..99efa8063a --- /dev/null +++ b/Task/FASTA-format/PL-M/fasta-format.plm @@ -0,0 +1,97 @@ +100H: /* DISPLAY THE CONTENTS OF A FASTA FORMT FILE */ + + DECLARE FALSE LITERALLY '0', TRUE LITERALLY '0FFH'; + DECLARE NL$CHAR LITERALLY '0AH'; /* NEWLINE: CHAR 10 */ + DECLARE CR$CHAR LITERALLY '0DH'; /* CARRIAGE RETURN, CHAR 13 */ + DECLARE EOF$CHAR LITERALLY '26'; /* EOF: CTRL-Z */ + /* CP/M BDOS SYSTEM CALL, RETURNS A VALUE */ + BDOS: PROCEDURE( FN, ARG )BYTE; DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; + /* CP/M BDOS SYSTEM CALL, NO RETURN VALUE */ + BDOS$P: PROCEDURE( FN, ARG ); DECLARE FN BYTE, ARG ADDRESS; GOTO 5; END; + EXIT: PROCEDURE; CALL BDOS$P( 0, 0 ); END; /* CP/M SYSTEM RESET */ + PR$CHAR: PROCEDURE( C ); DECLARE C BYTE; CALL BDOS$P( 2, C ); END; + PR$STRING: PROCEDURE( S ); DECLARE S ADDRESS; CALL BDOS$P( 9, S ); END; + PR$NL: PROCEDURE; CALL PR$STRING( .( 0DH, NL$CHAR, '$' ) ); END; + FL$EXISTS: PROCEDURE( FCB )BYTE; /* RETURNS TRUE IF THE FILE NAMED IN THE */ + DECLARE FCB ADDRESS; /* FCB EXISTS */ + RETURN ( BDOS( 17, FCB ) < 4 ); + END FL$EXISTS ; + FL$OPEN: PROCEDURE( FCB )BYTE; /* OPEN THE FILE WITH THE SPECIFIED FCB */ + DECLARE FCB ADDRESS; + RETURN ( BDOS( 15, FCB ) < 4 ); + END FL$OPEN; + FL$READ: PROCEDURE( FCB )BYTE; /* READ THE NEXT RECORD FROM FCB */ + DECLARE FCB ADDRESS; + RETURN ( BDOS( 20, FCB ) = 0 ); + END FL$READ; + FL$CLOSE: PROCEDURE( FCB )BYTE; /* CLOSE THE FILE WITH THE SPECIFIED FCB */ + DECLARE FCB ADDRESS; + RETURN ( BDOS( 16, FCB ) < 4 ); + END FL$CLOSE; + + /* I/O USES FILE CONTROL BLOCKS CONTAINING THE FILE-NAME, POSITION, ETC. */ + /* WHEN THE PROGRAM IS RUN, THE CCP WILL FIRST PARSE THE COMMAND LINE AND */ + /* PUT THE FIRST PARAMETER IN FCB1, THE SECOND PARAMETER IN FCB2 */ + /* BUT FCB2 OVERLAYS THE END OF FCB1 AND THE DMA BUFFER OVERLAYS THE END */ + /* OF FCB2 */ + + DECLARE FCB$SIZE LITERALLY '36'; /* SIZE OF A FCB */ + DECLARE FCB1 LITERALLY '5CH'; /* ADDRESS OF FIRST FCB */ + DECLARE FCB2 LITERALLY '6CH'; /* ADDRESS OF SECOND FCB */ + DECLARE DMA$BUFFER LITERALLY '80H'; /* DEFAULT DMA BUFFER ADDRESS */ + DECLARE DMA$SIZE LITERALLY '128'; /* SIZE OF THE DMA BUFFER */ + + DECLARE F$PTR ADDRESS, F$CHAR BASED F$PTR BYTE; + + /* CLEAR THE PARTS OF FCB1 OVERLAYED BY FCB2 */ + DO F$PTR = FCB1 + 12 TO FCB1 + ( FCB$SIZE - 1 ); + F$CHAR = 0; + END; + + /* SHOW THE FASTA DATA, IF THE FILE EXISTS */ + IF NOT FL$EXISTS( FCB1 ) THEN DO; /* THE FILE DOES NOT EXIST */ + CALL PR$STRING( .'FILE NOT FOUND$' );CALL PR$NL; + END; + ELSE IF NOT FL$OPEN( FCB1 ) THEN DO; /* UNABLE TO OPEN THE FILE */ + CALL PR$STRING( .'UNABLE TO OPEN THE FILE$' );CALL PR$NL; + END; + ELSE DO; /* FILE EXISTS AND OPENED OK - ATTEMPT TO SHOW THE DATA */ + DECLARE ( BOL, GOT$RCD, IS$HEADING ) BYTE, DMA$END ADDRESS; + DMA$END = DMA$BUFFER + ( DMA$SIZE - 1 ); + GOT$RCD = FL$READ( FCB1 ); /* GET THE FIRST RECORD */ + F$PTR = DMA$BUFFER; + BOL = TRUE; + IS$HEADING = FALSE; + DO WHILE GOT$RCD; + IF F$PTR > DMA$END THEN DO; /* END OF BUFFER */ + GOT$RCD = FL$READ( FCB1 ); /* GET THE NEXT RECORDD */ + F$PTR = DMA$BUFFER; + END; + ELSE IF F$CHAR = NL$CHAR THEN DO; /* END OF LINE */ + IF IS$HEADING THEN DO; + CALL PR$STRING( .': $' ); + IS$HEADING = FALSE; + END; + BOL = TRUE; + END; + ELSE IF F$CHAR = CR$CHAR THEN DO; END; /* IGNORE CARRIAGE RETURN */ + ELSE IF F$CHAR = EOF$CHAR THEN GOT$RCD = FALSE; /* END OF FILE */ + ELSE DO; /* HAVE ANOTHER CHARACTER */ + IF NOT BOL THEN CALL PR$CHAR( F$CHAR ); /* NOT FIRST CHARACTER */ + ELSE DO; /* FIRST CHARACTER - CHECK FOR A HEADING LINE */ + BOL = FALSE; + IF IS$HEADING := F$CHAR = '>' THEN CALL PR$NL; + ELSE CALL PR$CHAR( F$CHAR ); + END; + END; + F$PTR = F$PTR + 1; + END; + /* CLOSE THE FILE */ + IF NOT FL$CLOSE( FCB1 ) THEN DO; + CALL PR$STRING( .'UNABLE TO CLOSE THE FILE$' ); CALL PR$NL; + END; + END; + + CALL EXIT; + +EOF diff --git a/Task/Factorial-primes/ALGOL-68/factorial-primes.alg b/Task/Factorial-primes/ALGOL-68/factorial-primes.alg index 2cc56e0011..86395265f7 100644 --- a/Task/Factorial-primes/ALGOL-68/factorial-primes.alg +++ b/Task/Factorial-primes/ALGOL-68/factorial-primes.alg @@ -10,27 +10,24 @@ BEGIN # find some factorial primes - primes that are f - 1 or f + 1 # FOR i FROM 3 BY 2 TO SHORTEN ENTIER long sqrt(p) WHILE prime := p MOD i /= 0 DO SKIP OD; prime FI; -# end of code based on the primality by trial divisio task # +# end of code based on the primality by trial division task # - PROC show factorial prime = ( INT fp number, INT n, CHAR fp op, LONG INT fp )VOID: - print( ( whole( fp number, -2 ), ":", whole( n, -4 ) - , "! ", fp op, " 1 = ", whole( fp, 0 ) - , newline - ) - ); LONG INT f := 1; INT fp count := 0; FOR n WHILE fp count < 10 DO f *:= n; - IF LONG INT fp = f - 1; - is prime( fp ) - THEN - show factorial prime( fp count +:= 1, n, "-", fp ) - FI; - IF LONG INT fp = f + 1; - is prime( fp ) - THEN - show factorial prime( fp count +:= 1, n, "+", fp ) - FI + CHAR fp op := "-"; + FOR offset FROM -1 BY 2 TO 1 DO + IF LONG INT fp = f + offset; + is prime( fp ) + THEN + print( ( whole( fp count +:= 1, -2 ), ":", whole( n, -4 ) + , "! ", fp op, " 1 = ", whole( fp, 0 ) + , newline + ) + ) + FI; + fp op := "+" + OD OD END diff --git a/Task/Factorial-primes/Lua/factorial-primes.lua b/Task/Factorial-primes/Lua/factorial-primes.lua new file mode 100644 index 0000000000..3720b9e0cb --- /dev/null +++ b/Task/Factorial-primes/Lua/factorial-primes.lua @@ -0,0 +1,39 @@ +do -- find some factorial primes - primes that are f - 1 or f + 1 + -- for some factorial f + + function isPrime( p ) + if p <= 1 or p % 2 == 0 then + return p == 2 + else + local prime = true + local i = 3 + local rootP = math.floor( math.sqrt( p ) ) + while i <= rootP and prime do + prime = p % i ~= 0 + i = i + 1 + end + return prime + end + end + + local f = 1 + local fpCount = 0 + local n = 0 + local fpOp = "" + while fpCount < 10 do + n = n + 1 + f = f * n + fpOp = "-" + for fp = f - 1, f + 1, 2 do + if isPrime( fp ) then + fpCount = fpCount + 1 + io.write( string.format( "%2d", fpCount ), ":" + , string.format( "%4d", n ), "! " + , fpOp, " 1 = ", fp, "\n" + ) + end + fpOp = "+" + end + end + +end diff --git a/Task/Factorial-primes/Sidef/factorial-primes.sidef b/Task/Factorial-primes/Sidef/factorial-primes.sidef new file mode 100644 index 0000000000..4ba2cf3cda --- /dev/null +++ b/Task/Factorial-primes/Sidef/factorial-primes.sidef @@ -0,0 +1,14 @@ +var factorial_primes = Enumerator({|f| + for k in (1..Inf) { + if (k!-1 -> is_prime) { f([k, -1]) } + if (k!+1 -> is_prime) { f([k, +1]) } + } +}) + +func abr(v) { + v.len <= 40 ? v : (v.to_s.first(20) + '..' + v.to_s.last(20) + " (#{v.len} digits)") +} + +factorial_primes.first(30).each_2d {|k,i| + printf("%3d! %s %d = %s\n", k, (i.sgn < 0 ? '-' : '+'), i.abs, abr(k! + i)) +} diff --git a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef index 5f3369d4fd..cbded11915 100644 --- a/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef +++ b/Task/Fibonacci-n-step-number-sequences/Sidef/fibonacci-n-step-number-sequences-1.sidef @@ -2,7 +2,7 @@ func fib(n, xs=[1], k=20) { loop { var len = xs.len len >= k && break - xs << xs.ft(max(0, len - n)).sum + xs << xs.slice(max(0, len - n)).sum } return xs } diff --git a/Task/Fibonacci-sequence/Odin/fibonacci-sequence.odin b/Task/Fibonacci-sequence/Odin/fibonacci-sequence.odin new file mode 100644 index 0000000000..c780e166d5 --- /dev/null +++ b/Task/Fibonacci-sequence/Odin/fibonacci-sequence.odin @@ -0,0 +1,22 @@ +package fib +import "core:fmt" + +main :: proc() { + fmt.println("\nFibonacci Seq - starting n and n+1 from 0 and 1:") + fmt.println("------------------------------------------------") + for j: u128 = 0; j <= 20; j += 1 { + fmt.println("n:", j, "\tFib:", fibi(j)) + } +} + +fibi :: proc(n: u128) -> u128 { + if n < 2 { + return n + } + a, b: u128 = 0, 1 + for _ in 2..=n { + a += b + a, b = b, a + } + return b +} diff --git a/Task/Filter/EMal/filter.emal b/Task/Filter/EMal/filter.emal new file mode 100644 index 0000000000..b82a0b0f18 --- /dev/null +++ b/Task/Filter/EMal/filter.emal @@ -0,0 +1 @@ +writeLine(range(1, 11).filter([i%3]}#{[i%5]}"||i}*100 +{>"#{[.%3]}#{[.%5]}"||_}<<1..100 diff --git a/Task/FizzBuzz/Swift/fizzbuzz-3.swift b/Task/FizzBuzz/Swift/fizzbuzz-3.swift new file mode 100644 index 0000000000..d337cf2b97 --- /dev/null +++ b/Task/FizzBuzz/Swift/fizzbuzz-3.swift @@ -0,0 +1,28 @@ +import Foundation + +let formats: [String] = [ + "%d", + "%d", + "fizz", + "%d", + "buzz", + "fizz", + "%d", + "%d", + "fizz", + "buzz", + "%d", + "fizz", + "%d", + "%d", + "fizzbuzz", +] + +var count = 0 +var index = 0 +while count < 100 { + count += 1 + print(String(format: formats[index], count)) + index += 1 + index %= 15 +} diff --git a/Task/Fractran/Julia/fractran.julia b/Task/Fractran/Julia/fractran.julia index 261db566c1..a590a05890 100644 --- a/Task/Fractran/Julia/fractran.julia +++ b/Task/Fractran/Julia/fractran.julia @@ -1,32 +1,36 @@ # FRACTRAN interpreter implemented as an iterable struct using .Iterators: filter, map, take -import Base: iterate, show struct Fractran rs::Vector{Rational{BigInt}} i₀::BigInt + limit::Int end -iterate(f::Fractran, i = f.i₀) = +Base.iterate(f::Fractran, i = f.i₀) = for r in f.rs - if iszero(i % r.den) # faster than isinteger(i*r) + if iszero(i % r.den) i = i ÷ r.den * r.num - return (i, i) + return i, i end end -run(f::Fractran) = map(trailing_zeros, filter(ispow2, f)) +interpret(f::Fractran) = + take( + map(trailing_zeros, + filter(ispow2, f)) + f.limit) -show(io::IO, f::Fractran) = join(io, take(run(f), 30), ' ') +Base.show(io::IO, f::Fractran) = + join(io, interpret(f), ' ') macro code_str(s) - eval(Meta.parse("[" * replace(s, "/" => "//") * "]")) + [eval(Meta.parse(replace(t, "/" => "//"))) for t ∈ split(s)] end -# Example FRACTRAN program generating primes -primes = Fractran(code"17/91, 78/85, 19/51, 23/38, 29/33, 77/29, 95/23, - 77/19, 1/17, 11/13, 13/11, 15/14, 15/2, 55/1", 2) +primes = Fractran(code"17/91 78/85 19/51 23/38 29/33 77/29 95/23 + 77/19 1/17 11/13 13/11 15/14 15/2 55/1", 2, 30) # Output println("First 25 iterations of FRACTRAN program 'primes':\n2 ", diff --git a/Task/Greatest-subsequential-sum/Sidef/greatest-subsequential-sum.sidef b/Task/Greatest-subsequential-sum/Sidef/greatest-subsequential-sum.sidef index b77d67e5c2..5b7d6e7a88 100644 --- a/Task/Greatest-subsequential-sum/Sidef/greatest-subsequential-sum.sidef +++ b/Task/Greatest-subsequential-sum/Sidef/greatest-subsequential-sum.sidef @@ -1,19 +1,19 @@ func maxsubseq(*a) { - var (start, end, sum, maxsum) = (-1, -1, 0, 0); + var (start, end, sum, maxsum) = (-1, -1, 0, 0) a.each_kv { |i, x| - sum += x; + sum += x if (maxsum < sum) { - maxsum = sum; - end = i; + maxsum = sum + end = i } elsif (sum < 0) { - sum = 0; - start = i; + sum = 0 + start = i } - }; - a.ft(start+1, end); + } + a.slice(start+1).first(end-start) } - -say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1); -say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1); -say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1); +  +say maxsubseq(-1, -2, 3, 5, 6, -2, -1, 4, -4, 2, -1) +say maxsubseq(-2, -2, -1, 3, 5, 6, -1, 4, -4, 2, -1) +say maxsubseq(-2, -2, -1, -3, -5, -6, -1, -4, -4, -2, -1) diff --git a/Task/Harmonic-series/Craft-Basic/harmonic-series.basic b/Task/Harmonic-series/Craft-Basic/harmonic-series.basic new file mode 100644 index 0000000000..0aabb0830e --- /dev/null +++ b/Task/Harmonic-series/Craft-Basic/harmonic-series.basic @@ -0,0 +1,34 @@ +precision 5 + +print "the first twenty harmonic numbers are:" + +for n = 1 to 20 + + let h = h + 1 / n + print n, tab, h + +next n + +print newline, "the nth index of the first harmonic number that exceeds the nth integer:" + +let h = 1 +let n = 2 + +for i = 2 to 10 + + do + + if h < i then + + let h = h + 1 / n + let n = n + 1 + + endif + + wait + + loop h < i + + print tab, n - 1, + +next i diff --git a/Task/Harmonic-series/Tcl/harmonic-series.tcl b/Task/Harmonic-series/Tcl/harmonic-series.tcl new file mode 100644 index 0000000000..24a829deec --- /dev/null +++ b/Task/Harmonic-series/Tcl/harmonic-series.tcl @@ -0,0 +1,30 @@ +# Task 1 +proc harmonic {n} { + if {$n < 1 || $n != [expr {floor($n)}]} { + error "Argument to harmonic function is not a natural number" + } + set Hn 1 + for {set i 2} {$i <= $n} {incr i} { + set Hn [expr {$Hn + (1.0/$i)}] + } + return $Hn +} + +# Task 2 +for {set x 1} {$x <= 20} {incr x} { + set Hx [harmonic $x] + puts "$x: $Hx" +} + +# Task 3 /stretch +set x 0 +set lastInt 1 +while {$lastInt <= 10} { + incr x + set Hx [harmonic $x] + if {$Hx > $lastInt} { + puts -nonewline "The first harmonic number above $lastInt" + puts " is $Hx at position $x" + incr lastInt + } +} diff --git a/Task/Hash-from-two-arrays/EMal/hash-from-two-arrays.emal b/Task/Hash-from-two-arrays/EMal/hash-from-two-arrays.emal new file mode 100644 index 0000000000..e95f8bd205 --- /dev/null +++ b/Task/Hash-from-two-arrays/EMal/hash-from-two-arrays.emal @@ -0,0 +1,4 @@ +List keys = var["hal", 666, int[1,2,3]] +List vals = var["ibm", "devil", 123] +Map hash = keys.zip(vals) +writeLine(hash) diff --git a/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-2.sidef b/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-2.sidef index 21c50bd482..eb85f13832 100644 --- a/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-2.sidef +++ b/Task/Hofstadter-Q-sequence/Sidef/hofstadter-q-sequence-2.sidef @@ -2,7 +2,7 @@ var Q = [0, 1, 1] 100_000.times { Q << (Q[-Q[-1]] + Q[-Q[-2]]) } -  -say "First 10 terms: #{Q.ft(1, 10)}" + +say "First 10 terms: #{Q.slice(1).first(10)}" say "Term 1000: #{Q[1000]}" say "Terms less than preceding in first 100k: #{2..100000->count{|i|Q[i] ": Lat +120 INPUT PROMPT "Enter longitude => ": Lng +130 INPUT PROMPT "Enter legal meridian => ": Ref +140 PRINT +150 OPTION ANGLE DEGREES +160 LET Slat = SIN(Lat) +170 PRINT " sine of latitude: "; Slat +180 PRINT " diff longitude: "; Lng - Ref +190 PRINT +200 PRINT "Hour, sun hour angle, dial hour line angle from 6am to 6pm" +210 FOR Hour = -6 TO 6 +220 LET HourAngle = 15 * Hour +230 LET HourAngle = HourAngle - (Lng - Ref) ! correct for longitude difference +240 LET HourLineAngle = ATN(Slat * TAN(HourAngle)) +250 PRINT USING "HR=###; HRA=####.###; HLA=####.###": Hour, HourAngle, HourLineAngle +260 NEXT Hour +270 END diff --git a/Task/Horners-rule-for-polynomial-evaluation/Sidef/horners-rule-for-polynomial-evaluation-2.sidef b/Task/Horners-rule-for-polynomial-evaluation/Sidef/horners-rule-for-polynomial-evaluation-2.sidef index 549b9a4a94..ef5e19f50f 100644 --- a/Task/Horners-rule-for-polynomial-evaluation/Sidef/horners-rule-for-polynomial-evaluation-2.sidef +++ b/Task/Horners-rule-for-polynomial-evaluation/Sidef/horners-rule-for-polynomial-evaluation-2.sidef @@ -1,6 +1,7 @@ func horner(coeff, x) { - coeff.len > 0 - && (coeff[0] + x*horner(coeff.ft(1), x)); + (coeff.len > 0) \ + ? (coeff[0] + x*horner(coeff.last(-1), x)) + : 0 } -say horner([-19, 7, -4, 6], 3); # => 128 +say horner([-19, 7, -4, 6], 3) # => 128 diff --git a/Task/Inheritance-Single/EMal/inheritance-single.emal b/Task/Inheritance-Single/EMal/inheritance-single.emal new file mode 100644 index 0000000000..0f0815cd61 --- /dev/null +++ b/Task/Inheritance-Single/EMal/inheritance-single.emal @@ -0,0 +1,16 @@ +in Org:RosettaCode +type Animal +model do end +type Dog extends Animal +model do end +type Cat extends Animal +model do end +type Lab extends Dog +model do end +type Collie extends Dog +model do end +type Main +var fuffy = Collie() +for each generic kind in generic[Animal, Dog, Cat, Lab, Collie] + writeLine("Fuffy " + when(Generic.check(kind, fuffy), "is", "is not") + " a " + Generic.name(kind)) +end diff --git a/Task/Julia-set/Transact-SQL/julia-set.sql b/Task/Julia-set/Transact-SQL/julia-set.sql new file mode 100644 index 0000000000..9e39cd2821 --- /dev/null +++ b/Task/Julia-set/Transact-SQL/julia-set.sql @@ -0,0 +1,113 @@ +-- Juila Set +-- SQL Server 2017 and above +SET NOCOUNT ON +GO + +-- Plot area 800 X 600 +DECLARE @width INT = 800 +DECLARE @height INT = 600 + +DECLARE @r_min DECIMAL (10, 8) = -1.5; +DECLARE @r_max DECIMAL (10, 8) = 1.5; +DECLARE @i_min DECIMAL (10, 8) = -1; +DECLARE @i_max DECIMAL (10, 8) = 1; + +DECLARE @zoom INT = 1, + @moveX INT = 0, + @moveY INT = 0; + +DECLARE @iter INT = 255; -- Iteration + +DROP TABLE IF EXISTS dbo.Numbers +DROP TABLE IF EXISTS dbo.julia_set; + +CREATE TABLE dbo.Numbers (n INT); + +-- Generate a number table of 1000 rows +;WITH N1(n) AS +( + SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL + SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL + SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 +), -- 10 +N2(n) AS (SELECT 1 FROM N1 CROSS JOIN N1 AS b), -- 10*10 +N3(n) AS (SELECT 1 FROM N1 CROSS JOIN N2) -- 10*100 +INSERT INTO dbo.Numbers (n) +SELECT n = ROW_NUMBER() OVER (ORDER BY n) +FROM N3 ORDER BY n; +/* +-- If the version is SQL Server 2022 and above +INSERT INTO dbo.Numbers (n) +SELECT value FROM GENERATE_SERIES(0, 1000); +*/ + +CREATE TABLE dbo.julia_set +( + a INT, + b INT, + c_re DECIMAL (10, 8), + c_im DECIMAL (10, 8), + z_re DECIMAL (10, 8) DEFAULT 0, + z_im DECIMAL (10, 8) DEFAULT 0, + znew_re DECIMAL (10, 8) DEFAULT 0, + znew_im DECIMAL (10, 8) DEFAULT 0, + steps INT DEFAULT 0, + active BIT DEFAULT 1, +) + +-- Store all the z_re, z_im with constant c_re, c_im corresponding to each point in the plot area +-- Generate 480,000 rows (800 X 600) +INSERT INTO dbo.julia_set (a, b, c_re, c_im, z_re, z_im, steps) +SELECT a.n as a, b.n as b + ,-0.7 AS c_re + ,0.27015 AS c_im + ,@r_max * (a.n - @width / 2) / (0.5 * @zoom * @width) + @moveX AS z_re + ,@i_max * (b.n - @height / 2) / (0.5 * @zoom * @height) + @moveY AS z_im + ,@iter as steps +FROM + ( + SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @width + ) as a +CROSS JOIN + ( + SELECT n - 1 as n FROM dbo.Numbers WHERE n <= @height + ) as b; + +-- Iteration +WHILE (@iter > 1) + BEGIN + + UPDATE dbo.julia_set + SET + znew_re = POWER(z_re,2)-POWER(z_im,2)+c_re, + znew_im = 2*z_re*z_im+c_im, + steps = steps-1 + WHERE active=1; + + UPDATE dbo.julia_set + SET + z_re=znew_re, + z_im=znew_im, + active= CASE + WHEN POWER(znew_re,2)+POWER(znew_im,2)>4 THEN 0 + ELSE 1 + END + WHERE active=1; + + SET @iter = @iter - 1; + END + +-- Generating PPM File +-- Save the below query results to a file with extension .ppm +-- NOTE : All the unwanted info like 'rows affected', 'completed time' etc. needs to be +-- removed from the file. Most of the image editing softwares and online viewers can display the .ppm file +SELECT 'P3' UNION ALL +SELECT CAST(@width AS VARCHAR(5)) + ' ' + CAST(@height AS VARCHAR(5)) UNION ALL +SELECT '255' UNION ALL +SELECT + STRING_AGG(CAST(CASE WHEN active = 1 THEN 0 ELSE 55 + steps % 200 END AS VARCHAR(MAX)) + ' ' -- R + + CAST(CASE WHEN active = 1 THEN 0 ELSE 55+POWER(steps,3) % 200 END AS VARCHAR(MAX)) + ' ' -- G + + CAST(CASE WHEN active = 1 THEN 0 ELSE 55+ POWER(steps,2) % 200 END AS VARCHAR(MAX)) -- B + , ' ') WITHIN GROUP (ORDER BY a, b) +FROM dbo.julia_set +GROUP BY a, b diff --git a/Task/Largest-proper-divisor-of-n/ANSI-BASIC/largest-proper-divisor-of-n.basic b/Task/Largest-proper-divisor-of-n/ANSI-BASIC/largest-proper-divisor-of-n.basic new file mode 100644 index 0000000000..083a827165 --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/ANSI-BASIC/largest-proper-divisor-of-n.basic @@ -0,0 +1,14 @@ +100 REM Largest proper divisor of n +110 PRINT "The largest proper divisor of n is:" +120 PRINT +130 PRINT USING " ## ##": 1, 1; +140 FOR I = 3 TO 100 +150 FOR J = I - 1 TO 1 STEP -1 +160 IF MOD(I, J) = 0 THEN +170 PRINT USING "###": J; +180 EXIT FOR +290 END IF +200 NEXT J +210 IF MOD(I, 10) = 0 THEN PRINT +220 NEXT I +230 END diff --git a/Task/Largest-proper-divisor-of-n/Craft-Basic/largest-proper-divisor-of-n.basic b/Task/Largest-proper-divisor-of-n/Craft-Basic/largest-proper-divisor-of-n.basic new file mode 100644 index 0000000000..55f825f975 --- /dev/null +++ b/Task/Largest-proper-divisor-of-n/Craft-Basic/largest-proper-divisor-of-n.basic @@ -0,0 +1,25 @@ +print "Largest proper divisor of n is:" +print tab, "1", tab, "1", + +for i = 3 to 100 + + for j = i - 1 to 1 step -1 + + if i mod j = 0 then + + print tab, j, + break j + + endif + + wait + + next j + + if i mod 10 = 0 then + + print + + endif + +next i diff --git a/Task/Last-Friday-of-each-month/M2000-Interpreter/last-friday-of-each-month.m2000 b/Task/Last-Friday-of-each-month/M2000-Interpreter/last-friday-of-each-month.m2000 new file mode 100644 index 0000000000..fefc73a49c --- /dev/null +++ b/Task/Last-Friday-of-each-month/M2000-Interpreter/last-friday-of-each-month.m2000 @@ -0,0 +1,24 @@ +module lastfriday { + string year + integer y% + input "Year (e.g. 2023):", y% + year=str$(y%,"") + date a="1/1/"+year + date a1="31/12/"+year + double i, b=a, c=a1 + + for i=b to b+6 + if val(date$(i, 1033, "d"))=6 then exit for + next + document result$="Last Friday per month for year " + year + {: + } + for i=i+7 to c step 7 + if val(date$(i, 1033, "M")) <>val(date$(i+7, 1033, "M")) then + result$=date$(i, 1033, "M"+chr$(9)+"dd") + { + } + end if + next + report result$ + clipboard result$ +} +lastfriday diff --git a/Task/Levenshtein-distance-Alignment/Sidef/levenshtein-distance-alignment.sidef b/Task/Levenshtein-distance-Alignment/Sidef/levenshtein-distance-alignment.sidef index 7b1d515fda..a437cfb2f2 100644 --- a/Task/Levenshtein-distance-Alignment/Sidef/levenshtein-distance-alignment.sidef +++ b/Task/Levenshtein-distance-Alignment/Sidef/levenshtein-distance-alignment.sidef @@ -3,8 +3,8 @@ func align(s, t) { t.chars!.prepend!('^') var A = [] - {|i| A[i][0]{@|} = (i, s.ft(1, i).join, '~' * i) } << ^s - {|i| A[0][i]{@|} = (i, '-' * i, t.ft(1, i).join) } << ^t + {|i| A[i][0]{@|} = (i, s.slice(1).first(i).join, '~' * i) } << ^s + {|i| A[0][i]{@|} = (i, '-' * i, t.slice(1).first(i).join) } << ^t for i (1 .. s.end) { for j (1 .. t.end) { diff --git a/Task/Levenshtein-distance/Sidef/levenshtein-distance-1.sidef b/Task/Levenshtein-distance/Sidef/levenshtein-distance-1.sidef index 35dcc34c37..fd64fe7983 100644 --- a/Task/Levenshtein-distance/Sidef/levenshtein-distance-1.sidef +++ b/Task/Levenshtein-distance/Sidef/levenshtein-distance-1.sidef @@ -3,8 +3,8 @@ func lev(s, t) is cached { s || return t.len t || return s.len   - var s1 = s.ft(1) - var t1 = t.ft(1) + var s1 = s.slice(1) + var t1 = t.slice(1)   s[0] == t[0] ? __FUNC__(s1, t1)  : 1+Math.min( diff --git a/Task/Longest-common-subsequence/Sidef/longest-common-subsequence.sidef b/Task/Longest-common-subsequence/Sidef/longest-common-subsequence.sidef index 7e947eb97b..974abc7703 100644 --- a/Task/Longest-common-subsequence/Sidef/longest-common-subsequence.sidef +++ b/Task/Longest-common-subsequence/Sidef/longest-common-subsequence.sidef @@ -1,16 +1,16 @@ func lcs(xstr, ystr) is cached { - xstr.is_empty && return xstr; - ystr.is_empty && return ystr; + xstr.is_empty && return xstr + ystr.is_empty && return ystr - var(x, xs, y, ys) = (xstr.ft(0,0), xstr.ft(1), - ystr.ft(0,0), ystr.ft(1)); + var(x, xs, y, ys) = (xstr.first(1), xstr.slice(1), + ystr.first(1), ystr.slice(1)) if (x == y) { x + lcs(xs, ys) } else { - [lcs(xstr, ys), lcs(xs, ystr)].max_by { .len }; + [lcs(xstr, ys), lcs(xs, ystr)].max_by { .len } } } -say lcs("thisisatest", "testing123testing"); +say lcs("thisisatest", "testing123testing") diff --git a/Task/MD5-Implementation/Sidef/md5-implementation.sidef b/Task/MD5-Implementation/Sidef/md5-implementation.sidef index b8eb4937fb..6ca1705cc7 100644 --- a/Task/MD5-Implementation/Sidef/md5-implementation.sidef +++ b/Task/MD5-Implementation/Sidef/md5-implementation.sidef @@ -82,7 +82,7 @@ class MD5(String msg) { var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476] for i in (range(0, M.end, 16)) { - md5_block(H, M.ft(i, i+15)) + md5_block(H, M.slice(i).first(16)) } little_endian(8, 4, H) diff --git a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia index eae6beb86c..272d45f3ac 100644 --- a/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia +++ b/Task/Mandelbrot-set/Julia/mandelbrot-set-4.julia @@ -5,7 +5,7 @@ d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) direction, height = 45, 1.5 # direction and height of the incoming light -v = exp(direction / 180 * pi * im) # unit 2D vector in this direction +stripes, damping = 4, 2.0 # stripe density and damping parameter x = range(0, 2, length=d+1) y = range(0, 2 * h / d, length=h+1) @@ -14,31 +14,29 @@ A, B = collect(x) .- 1, collect(y) .- h / d C = (2.0 + 1.0im) .* (A' .+ B .* im) .- 0.5 Z, dZ, ddZ = zero(C), zero(C), zero(C) -D, T = zeros(size(C)), zeros(size(C)) +D, S, T = zeros(size(C)), zeros(size(C)), zeros(size(C)) for k in 1:n - M = abs2.(Z) .< abs2(r) + M = abs.(Z) .< r + S[M], T[M] = S[M] .+ cos.(stripes .* angle.(Z[M])), T[M] .+ 1 Z[M], dZ[M], ddZ[M] = Z[M] .^ 2 .+ C[M], 2 .* Z[M] .* dZ[M] .+ 1, 2 .* (dZ[M] .^ 2 .+ Z[M] .* ddZ[M]) end -N = abs.(Z) .> 2 # exterior distance estimation -D[N] = log.(abs.(Z[N])) .* abs.(Z[N]) ./ abs.(dZ[N]) +N = abs.(Z) .>= r # normal map effect 1 (potential function) +P, Q = S[N] ./ T[N], (S[N] .+ cos.(stripes .* angle.(Z[N]))) ./ (T[N] .+ 1) +F = log2.(log.(abs.(Z[N])) ./ log(r)) # fraction between 0 and 1 (for interpolation) +R = Q .+ (P .- Q) .* F .* F .* (3 .- 2 .* F) # hermite interpolation (r is between q and p) +U, H = Z[N] ./ dZ[N], 1 .+ R ./ damping # normal vectors to the equipotential lines and height perturbation +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction +D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ H .* height) ./ (1 + height), 0) -heatmap(D .^ 0.1, c=:balance) -savefig("Mandelbrot_distance_est.png") - -N = abs.(Z) .> 2 # normal map effect 1 (potential function) -U = Z[N] ./ dZ[N] # normal vectors to the equipotential lines -U, S = U ./ abs.(U), 1 .+ sin.(100 .* angle.(U)) ./ 10 # unit normal vectors and stripes -T[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ S .* height) ./ (1 + height), 0) - -heatmap(T .^ 1.0, c=:bone_1) +heatmap(D .^ 1.0, c=:bone_1) savefig("Mandelbrot_normal_map_1.png") -N = abs.(Z) .> 2 # normal map effect 2 (distance estimation) +N = abs.(Z) .>= r # normal map effect 2 (distance estimation) U = Z[N] .* dZ[N] .* ((1 .+ log.(abs.(Z[N]))) .* conj.(dZ[N] .^ 2) .- log.(abs.(Z[N])) .* conj.(Z[N] .* ddZ[N])) -U = U ./ abs.(U) # unit normal vectors to the equidistant lines -T[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) +U, v = U ./ abs.(U), exp(direction / 180 * pi * im) # unit normal vectors and vector in light direction +D[N] = max.((real.(U) .* real(v) .+ imag.(U) .* imag(v) .+ height) ./ (1 + height), 0) -heatmap(T .^ 1.0, c=:afmhot) +heatmap(D .^ 1.0, c=:afmhot) savefig("Mandelbrot_normal_map_2.png") diff --git a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py index 88a68eb849..c7acbea306 100644 --- a/Task/Mandelbrot-set/Python/mandelbrot-set-5.py +++ b/Task/Mandelbrot-set/Python/mandelbrot-set-5.py @@ -5,7 +5,7 @@ d, h = 800, 500 # pixel density (= image width) and image height n, r = 200, 500 # number of iterations and escape radius (r > 2) direction, height = 45, 1.5 # direction and height of the incoming light -v = np.exp(direction / 180 * np.pi * 1j) # unit 2D vector in this direction +stripes, damping = 4, 2.0 # stripe density and damping parameter x = np.linspace(0, 2, num=d+1) y = np.linspace(0, 2 * h / d, num=h+1) @@ -14,30 +14,28 @@ A, B = np.meshgrid(x - 1, y - h / d) C = (2.0 + 1.0j) * (A + B * 1j) - 0.5 Z, dZ, ddZ = np.zeros_like(C), np.zeros_like(C), np.zeros_like(C) -D, T = np.zeros(C.shape), np.zeros(C.shape) +D, S, T = np.zeros(C.shape), np.zeros(C.shape), np.zeros(C.shape) for k in range(n): - M = Z.real ** 2 + Z.imag ** 2 < r ** 2 + M = abs(Z) < r + S[M], T[M] = S[M] + np.cos(stripes * np.angle(Z[M])), T[M] + 1 Z[M], dZ[M], ddZ[M] = Z[M] ** 2 + C[M], 2 * Z[M] * dZ[M] + 1, 2 * (dZ[M] ** 2 + Z[M] * ddZ[M]) -N = abs(Z) > 2 # exterior distance estimation -D[N] = np.log(abs(Z[N])) * abs(Z[N]) / abs(dZ[N]) +N = abs(Z) >= r # normal map effect 1 (potential function) +P, Q = S[N] / T[N], (S[N] + np.cos(stripes * np.angle(Z[N]))) / (T[N] + 1) +F = np.log2(np.log(np.abs(Z[N])) / np.log(r)) # fraction between 0 and 1 (for interpolation) +R = Q + (P - Q) * F * F * (3 - 2 * F) # hermite interpolation (r is between q and p) +U, H = Z[N] / dZ[N], 1 + R / damping # normal vectors to the equipotential lines and height perturbation +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction +D[N] = np.maximum((U.real * v.real + U.imag * v.imag + H * height) / (1 + height), 0) -plt.imshow(D ** 0.1, cmap=plt.cm.twilight_shifted, origin="lower") -plt.savefig("Mandelbrot_distance_est.png", dpi=200) - -N = abs(Z) > 2 # normal map effect 1 (potential function) -U = Z[N] / dZ[N] # normal vectors to the equipotential lines -U, S = U / abs(U), 1 + np.sin(100 * np.angle(U)) / 10 # unit normal vectors and stripes -T[N] = np.maximum((U.real * v.real + U.imag * v.imag + S * height) / (1 + height), 0) - -plt.imshow(T ** 1.0, cmap=plt.cm.bone, origin="lower") +plt.imshow(D ** 1.0, cmap=plt.cm.bone, origin="lower") plt.savefig("Mandelbrot_normal_map_1.png", dpi=200) -N = abs(Z) > 2 # normal map effect 2 (distance estimation) +N = abs(Z) >= r # normal map effect 2 (distance estimation) U = Z[N] * dZ[N] * ((1 + np.log(abs(Z[N]))) * np.conj(dZ[N] ** 2) - np.log(abs(Z[N])) * np.conj(Z[N] * ddZ[N])) -U = U / abs(U) # unit normal vectors to the equidistant lines -T[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) +U, v = U / abs(U), np.exp(direction / 180 * np.pi * 1j) # unit normal vectors and vector in light direction +D[N] = np.maximum((U.real * v.real + U.imag * v.imag + height) / (1 + height), 0) -plt.imshow(T ** 1.0, cmap=plt.cm.afmhot, origin="lower") +plt.imshow(D ** 1.0, cmap=plt.cm.afmhot, origin="lower") plt.savefig("Mandelbrot_normal_map_2.png", dpi=200) diff --git a/Task/Mian-Chowla-sequence/Sidef/mian-chowla-sequence.sidef b/Task/Mian-Chowla-sequence/Sidef/mian-chowla-sequence.sidef index e3f4b8c3e6..4789894103 100644 --- a/Task/Mian-Chowla-sequence/Sidef/mian-chowla-sequence.sidef +++ b/Task/Mian-Chowla-sequence/Sidef/mian-chowla-sequence.sidef @@ -1,24 +1,24 @@ -var (n, sums, ts, mc) = (100, Set([2]), [], [1]) -var st = Time.micro_sec +var (n, sums, ts, mc) = (100, Set(2), [], [1]) +var st = Time.micro for i in (1 ..^ n) { for j in (mc[i-1]+1 .. Inf) { mc[i] = j for k in (0 .. i) { var sum = mc[k]+j - if (sums.exists(sum)) { + if (sums.has(sum)) { ts.clear break } ts << sum } if (ts.len > 0) { - sums = (sums|Set(ts...)) + sums |= Set(ts...) break } } } -var et = (Time.micro_sec - st) +var et = (Time.micro - st) var s = " of the Mian-Chowla sequence are:\n" -say "The first 30 terms#{s}#{mc.ft(0, 29).join(' ')}\n" -say "Terms 91 to 100#{s}#{mc.ft(90, 99).join(' ')}\n" +say "The first 30 terms#{s}#{mc.first(30).join(' ')}\n" +say "Terms 91 to 100#{s}#{mc.slice(90).first(10).join(' ')}\n" say "Computation time was #{et} seconds." diff --git a/Task/Middle-three-digits/Sidef/middle-three-digits.sidef b/Task/Middle-three-digits/Sidef/middle-three-digits.sidef index a70f125e1c..368894bafb 100644 --- a/Task/Middle-three-digits/Sidef/middle-three-digits.sidef +++ b/Task/Middle-three-digits/Sidef/middle-three-digits.sidef @@ -1,16 +1,16 @@ func middle_three(n) { - var l = n.len; + var l = n.len if (l < 3) { "#{n} is too short" } elsif (l.is_even) { "#{n} has an even number of digits" } else { - "The three middle digits of #{n} are: " + n.digits.ft(l-3 / 2, l/2 + 1).join + "The three middle digits of #{n} are: " + n.digits.slice((l-3)/2).first(3).flip.join } } var nums = %n( 123 12345 1234567 987654321 10001 -10001 -123 -100 100 -12345 1 2 -1 -10 2002 -2002 0 -); -nums.each { say middle_three(_) }; +) +nums.each { say middle_three(_) } diff --git a/Task/Minkowski-question-mark-function/F-Sharp/minkowski-question-mark-function.fs b/Task/Minkowski-question-mark-function/F-Sharp/minkowski-question-mark-function.fs new file mode 100644 index 0000000000..874212e9d8 --- /dev/null +++ b/Task/Minkowski-question-mark-function/F-Sharp/minkowski-question-mark-function.fs @@ -0,0 +1,13 @@ +// Minkowski question-mark function. Nigel Galloway: July 14th., 2023 +let fN g=let n=(int>>float)g in ((if g<0.0 then -1.0 else 1.0),abs n,abs (g-n)) +let fI(n,_,(nl,nh))(g,_,(gl,gh))=let l,h=nl+gl,nh+gh in ((n+g)/2.0,(float l)/(float h),(l,h)) +let fG n g=(max n g)-(min n g) +let fE(s,z,l)=Seq.unfold(fun(i,e)->let (n,g,_) as r=fI i e in Some((s*(z+n),s*(g+z)),if llet (n,g,_) as r=fI i e in Some((s*(z+n),s*(g+z)),if lSeq.pairwise|>Seq.find(fun((n,_),(g,_))->(fG n g)<2.328306437e-11) in n +let m2F g=let _,(_,n)=fE(fN g)|>Seq.pairwise|>Seq.find(fun((_,n),(_,g))->(fG n g)<2.328306437e-11) in n + +printfn $"?(φ) = 5/3 is %A{fG(f2M 1.61803398874989490253)(5.0/3.0)<2.328306437e-10}" +printfn $"?⁻¹(-5/9) = (√13-7)/6 is %A{fG(m2F(-5.0/9.0))((sqrt(13.0)-7.0)/6.0)<2.328306437e-10}" +let n=42.0/23.0 in printfn $"?⁻¹(?(n)) = n is %A{(fG(m2F(f2M n)) n)<2.328306437e-10}" +let n= -3.0/13.0 in printfn $"?(?⁻¹(n)) = n is %A{(fG(f2M(m2F n)) n)<2.328306437e-10}" diff --git a/Task/Modified-random-distribution/Rust/modified-random-distribution.rust b/Task/Modified-random-distribution/Rust/modified-random-distribution.rust new file mode 100644 index 0000000000..32f722c270 --- /dev/null +++ b/Task/Modified-random-distribution/Rust/modified-random-distribution.rust @@ -0,0 +1,29 @@ +use ndhistogram::{Histogram, ndhistogram, axis::Uniform}; +use rand::Rng; + +/// change x in [0.0, 1.0) to a split with minimum probability at 0.5 +fn modifier(x: f64) -> f64 { + if x < 0.5 { + return 2.0 * (0.5 - &x); + } else { + return 2.0 * (&x - 0.5); + } +} + +const WANTED: usize = 20_000; + +fn main() { + let mut hist = ndhistogram!(Uniform::new(19, -0.0, 1.0)); + let mut rng = rand::thread_rng(); + for _ in 0.. WANTED { + loop { + let x: f64 = rng.gen::(); + let y: f64 = rng.gen::(); + if y < modifier(x) { + hist.fill(&f64::from(x)); + break; + } + } + } + println!("{}", hist); +} diff --git a/Task/Multiplicative-order/11l/multiplicative-order.11l b/Task/Multiplicative-order/11l/multiplicative-order.11l index e1ecb91d5e..895e57c750 100644 --- a/Task/Multiplicative-order/11l/multiplicative-order.11l +++ b/Task/Multiplicative-order/11l/multiplicative-order.11l @@ -32,7 +32,7 @@ F factor(BigInt n) V e = 0 L V (div, rem) = divmod(nn, d) - I bit_length(rem) > 0 + I bits:length(rem) > 0 L.break nn = div e++ @@ -61,7 +61,7 @@ F moBachShallit58(BigInt a, BigInt n; pf) R mo F moTest(a, n) - I bit_length(a) < 100 + I bits:length(a) < 100 print(‘ord(’a‘)’, end' ‘’) E print(‘ord([big])’, end' ‘’) diff --git a/Task/N-queens-problem/Maxima/n-queens-problem-2.maxima b/Task/N-queens-problem/Maxima/n-queens-problem-2.maxima index 01e9f1f74d..ca4c2f27e6 100644 --- a/Task/N-queens-problem/Maxima/n-queens-problem-2.maxima +++ b/Task/N-queens-problem/Maxima/n-queens-problem-2.maxima @@ -1,11 +1,13 @@ /* Inspired by code from Python */ -Queens(N):=block([K,C,P,V,A,S,L:[]], +Queens(N):=block([K,C,P,V,L:[]], C: makelist(K,K,1,N), P: permutations(C), for V in P do ( - A: length(unique(makelist(V[K]+K, K, C))), - S: length(unique(makelist(V[K]-K, K, C))), - if is(A=N) and is(S=N) then L: cons(V, L) + if is(N=length(unique(makelist(V[K]+K, K, C)))) then ( + if is(N=length(unique(makelist(V[K]-K, K, C)))) then ( + L: endcons(V, L) + ) + ) ), L )$ diff --git a/Task/Narcissistic-decimal-number/Prolog/narcissistic-decimal-number.pro b/Task/Narcissistic-decimal-number/Prolog/narcissistic-decimal-number.pro index 1c9d676369..ec70ba8179 100644 --- a/Task/Narcissistic-decimal-number/Prolog/narcissistic-decimal-number.pro +++ b/Task/Narcissistic-decimal-number/Prolog/narcissistic-decimal-number.pro @@ -23,15 +23,15 @@ armstrong(Exp, PSum):- Min is 10^(Exp - 1) ; Min is 0 ), - Max is 10^Exp, + Max is 10^Exp - 1, combi(Exp, DigList, Comb), powSum(Comb, Exp, 0, PSum), between(Min, Max, PSum), digits(PSum, DList), sort(0, @=<, DList, DSort), % hold equal digits - ( PSum =:= 0, Comb = [0] -> % special case because - true % DList in digits(0, DList) is [] and not [0] - ; DSort = Comb + ( DSort = Comb; + PSum =:= 0, % special case because + Comb = [0] % DList in digits(0, DList) is [] and not [0] ). do:-between(1, 7, Exp), diff --git a/Task/Nautical-bell/FreeBASIC/nautical-bell.basic b/Task/Nautical-bell/FreeBASIC/nautical-bell.basic new file mode 100644 index 0000000000..a75fdda3e4 --- /dev/null +++ b/Task/Nautical-bell/FreeBASIC/nautical-bell.basic @@ -0,0 +1,18 @@ +Dim As Byte m = 0 +For n As Byte = 0 To 23 + If n = 23 Then + Print " 23" + ":30" + " = " + "7 bells" + Else + m += 1 + Print ""; n Mod 23; ":30"; " ="; m; " bells" + End If + If n = 23 Then + Print " 00" + ":00" + " = " + "8 bells" + Else + m += 1 + Print ""; (n Mod 23+1); ":00"; " ="; m; " bells" + If m = 8 Then m = 0 + End If +Next n + +Sleep diff --git a/Task/Next-highest-int-from-digits/ALGOL-68/next-highest-int-from-digits.alg b/Task/Next-highest-int-from-digits/ALGOL-68/next-highest-int-from-digits.alg new file mode 100644 index 0000000000..5685119acb --- /dev/null +++ b/Task/Next-highest-int-from-digits/ALGOL-68/next-highest-int-from-digits.alg @@ -0,0 +1,66 @@ +BEGIN # find the next integer > a given integer with the same digits # + + OP - = ( CHAR a, b )INT: ABS a - ABS b; # character subtraction # + PROC swap = ( REF STRING s, INT a, b )VOID: # swap chars at a and b in s # + BEGIN CHAR t = s[ a ]; s[ a ] := s[ b ]; s[ b ] := t END; + + # returns the next integer greater than v with the same digits as v # + OP NEXT = ( LONG INT v )LONG INT: + BEGIN + LONG INT result := 0; + STRING s := whole( v, 0 ); + INT c pos := UPB s - 1; + # find the rightmost digit that has a lower digit to the left # + WHILE IF c pos < LWB s + THEN FALSE + ELSE s[ c pos ] >= s[ c pos + 1 ] + FI + DO + c pos -:=1 + OD; + IF c pos >= LWB s THEN + # the digit at c pos is lower than one to its right # + # swap the lower digit with the smallest right digit greater # + # than the lower digit # + CHAR c = s[ c pos ]; + INT min pos := c pos + 1; + INT min diff := s[ c pos + 1 ] - c; + FOR m pos FROM c pos + 2 TO UPB s DO + IF s[ m pos ] > c THEN + IF INT this diff = s[ m pos ] - c; + this diff < min diff + THEN + min diff := this diff; + min pos := m pos + FI + FI + OD; + swap( s, min pos, c pos ); + # sort the right digits # + FOR u FROM UPB s - 1 BY -1 TO c pos + 1 + WHILE BOOL sorted := TRUE; + FOR p FROM c pos + 1 BY 1 TO u DO + IF s[ p ] > s[ p + 1 ] THEN + swap( s, p, p + 1 ); + sorted := FALSE + FI + OD; + NOT sorted + DO SKIP OD; + # convert back to an integer # + result := s[ LWB s ] - "0"; + FOR i FROM LWB s + 1 TO UPB s DO + result *:= 10 +:= s[ i ] - "0" + OD + FI; + result + END # NEXT # ; + + # task test cases # + []LONG INT tests = ( 0, 9, 12, 21, 12453, 738440, 45072010, 95322020 + , 9589776899767587796600 + ); + FOR i FROM LWB tests TO UPB tests DO + print( ( whole( tests[ i ], -24 ), " -> ", whole( NEXT tests[ i ], 0 ), newline ) ) + OD +END diff --git a/Task/Nth/ANSI-BASIC/nth.basic b/Task/Nth/ANSI-BASIC/nth.basic new file mode 100644 index 0000000000..e77d1eba79 --- /dev/null +++ b/Task/Nth/ANSI-BASIC/nth.basic @@ -0,0 +1,28 @@ +100 REM Nth +110 DECLARE EXTERNAL FUNCTION Suffix$ +120 DECLARE EXTERNAL SUB PrintImages +130 CALL PrintImages(0, 25) +140 CALL PrintImages(250, 265) +150 CALL PrintImages(1000, 1025) +160 END +170 REM +180 EXTERNAL SUB PrintImages(LoLim, HiLim) +190 FOR I = LoLim TO HiLim +200 PRINT STR$(I); Suffix$(I); " "; +210 NEXT I +220 PRINT +230 END SUB +240 REM +250 EXTERNAL FUNCTION Suffix$(N) +260 LET NMod10 = MOD(N, 10) +270 LET NMod100 = MOD(N, 100) +280 IF NMod10 = 1 AND NMod100 <> 11 THEN +290 LET Suffix$ = "st" +300 ELSEIF NMod10 = 2 AND NMod100 <> 12 THEN +310 LET Suffix$ = "nd" +320 ELSEIF NMod10 = 3 AND NMod100 <> 13 THEN +330 LET Suffix$ = "rd" +340 ELSE +350 LET Suffix$ = "th" +360 END IF +370 END FUNCTION diff --git a/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.alg b/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.alg new file mode 100644 index 0000000000..c9ac191df9 --- /dev/null +++ b/Task/Numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors/ALGOL-W/numbers-which-are-the-cube-roots-of-the-product-of-their-proper-divisors.alg @@ -0,0 +1,39 @@ +begin % find some numbers which are the cube roots of the product of their % + % proper divisors % + % the Online Encyclopedia of Integer Sequences states that these % + % numbers are 1 and those with eight divisors % + % NB: numbers with 8 divisors have 7 proper divisors % + + integer MAX_NUMBER; % maximum number we will consider % + MAX_NUMBER := 500000; + + begin + % form a table of proper divisor counts - pretend the pdc of 1 is 7 % + integer array pdc ( 1 :: MAX_NUMBER ); + integer nextToShow, cCount; + for i := 1 until MAX_NUMBER do pdc( i ) := 1; + pdc( 1 ) := 7; + for i := 2 until MAX_NUMBER do begin + for j := i + i step i until MAX_NUMBER do pdc( j ) := pdc( j ) + 1 + end; + % show the numbers which are the cube root of their proper divisor % + % product - equivalent to finding the numbers with a proper divisor % + % count of 7 ( we have "cheated" and set the pdc of 1 to 7 ) % + nextToShow := 500; + cCount := 0; + for n := 1 until MAX_NUMBER do begin + if pdc( n ) = 7 then begin + % found a suitable number % + cCount := cCount + 1; + if cCount <= 50 then begin + writeon( i_w := 3, s_w := 0, " ", n ); + if cCount rem 10 = 0 then write() + end + else if cCount = nextToShow then begin + write( i_w := 9, s_w := 0, cCount, "th: ", i_w := 1, n ); + nextToShow := nextToShow * 10 + end if_various_cCount_values + end if_pdc_n_eq_7 + end for_m + end +end. diff --git a/Task/Old-Russian-measure-of-length/Jq/old-russian-measure-of-length.jq b/Task/Old-Russian-measure-of-length/Jq/old-russian-measure-of-length.jq new file mode 100644 index 0000000000..80b441db64 --- /dev/null +++ b/Task/Old-Russian-measure-of-length/Jq/old-russian-measure-of-length.jq @@ -0,0 +1,70 @@ +def lpad($len): tostring | ($len - length) as $l | (" " * $l) + .; + +def Units: { + "arshin" : 0.7112, + "centimeter": 0.01, + "diuym" : 0.0254, + "fut" : 0.3048, + "kilometer" : 1000.0, + "liniya" : 0.00254, + "meter" : 1.0, + "milia" : 7467.6, + "piad" : 0.1778, + "sazhen" : 2.1336, + "tochka" : 0.000254, + "vershok" : 0.04445, + "versta" : 1066.8 +}; + +def cyrillic: { + "arshin" : "арши́н", + "centimeter": "сантиметр", + "diuym" : "дюйм", + "fut" : "фут", + "kilometer" : "километр", + "liniya" : "ли́ния", + "meter" : "метр", + "milia" : "ми́ля", + "piad" : "пядь", + "sazhen" : "саже́нь", + "tochka" : "то́чка", + "vershok" : "вершо́к", + "versta" : "верста́" +}; + +def request: + def explain: "number and unit of measurement expected vs \(.)" | error; + def check: + $ARGS.positional + | if length >= 2 + then (try (.[0] | tonumber) catch false) as $n + | (.[1] | sub("s$";"")) as $u + | if $n and Units[$u] then [$n, $u] + else explain + end + else explain + end; + check ; + +# Input: a number +# Delete unhelpful digits +def humanize($n): + tostring + | ( capture("^(?[0-9]*)[.](?0*)(?[0-9]*)$") + | (.head|length) as $hl + | if $hl > $n then .head + "." + elif .head | (. == "" or . == "0") + then .head + "." + .zeros + .tail[:1 + $n - $hl] + else .head + "." + (.zeros + .tail)[:1 + $n - $hl] + end ) // .; + +def display: + Units + | . as $Units + | request as [$n, $unit] + | "\($n) \($unit)\(if $n == 1 then "" else "s" end) ::", + (to_entries[] + | "\(.key|lpad(10)) : \(($n * $Units[$unit] / .value) | humanize(5)) \(cyrillic[.key])"), + "" ; + +display diff --git a/Task/Ordered-partitions/Sidef/ordered-partitions.sidef b/Task/Ordered-partitions/Sidef/ordered-partitions.sidef index cbbc96438c..d4a194200c 100644 --- a/Task/Ordered-partitions/Sidef/ordered-partitions.sidef +++ b/Task/Ordered-partitions/Sidef/ordered-partitions.sidef @@ -4,7 +4,7 @@ func partitions({.is_empty}) { [[]] } func part(s, args) { gather { s.combinations(args[0], { |*c| - part(s - c, args.ft(1)).each{|r| take([c] + r) } + part(s - c, args.slice(1)).each{|r| take([c] + r) } }) } } diff --git a/Task/Palindrome-detection/Sidef/palindrome-detection-1.sidef b/Task/Palindrome-detection/Sidef/palindrome-detection-1.sidef index cb6b3230b9..18832d44bc 100644 --- a/Task/Palindrome-detection/Sidef/palindrome-detection-1.sidef +++ b/Task/Palindrome-detection/Sidef/palindrome-detection-1.sidef @@ -1 +1 @@ -say "noon".is_palindrome; # true +say "noon".is_palindrome # true diff --git a/Task/Palindrome-detection/Sidef/palindrome-detection-3.sidef b/Task/Palindrome-detection/Sidef/palindrome-detection-3.sidef index 9e2c472599..63aa43ca08 100644 --- a/Task/Palindrome-detection/Sidef/palindrome-detection-3.sidef +++ b/Task/Palindrome-detection/Sidef/palindrome-detection-3.sidef @@ -2,10 +2,10 @@ func palindrome(s) { if (s.len <= 1) { true } - elsif (s.first != s.last) { + elsif (s.first != s.last) { false } else { - __FUNC__(s.ft(1, -2)) + __FUNC__(s.first(-1).last(-1)) } } diff --git a/Task/Particle-fountain/Lua/particle-fountain.lua b/Task/Particle-fountain/Lua/particle-fountain.lua new file mode 100644 index 0000000000..45e687e1c6 --- /dev/null +++ b/Task/Particle-fountain/Lua/particle-fountain.lua @@ -0,0 +1,38 @@ +-- Returns canvas of given width and height containing a circle +function initCanvas (width, height) + local c = love.graphics.newCanvas(width, height) + love.graphics.setCanvas(c) -- Switch to drawing on canvas 'c' + love.graphics.circle("fill", width / 2, height / 2, 2, 100) + love.graphics.setCanvas() -- Switch back to drawing on main screen + return c +end + +-- Returns particle system with given canvas +function initPartSys (image, maxParticles) + local ps = love.graphics.newParticleSystem(image, maxParticles) + ps:setParticleLifetime(3, 5) -- (min, max) + ps:setDirection(math.pi * 1.5) + ps:setSpeed(700) + ps:setLinearAcceleration(-100, 500, 100, 700) -- (minX, minY, maxX, maxY) + ps:setEmissionRate(1000) + ps:setPosition(400, 550) + ps:setColors(1, 1, 1, 1, 0, 0, 1, 0) -- Start solid white, fade to transluscent blue + return ps +end + +-- LÖVE callback that runs on program start +function love.load () + love.window.setTitle("Lua particle fountain") + local canvas = initCanvas(10, 10) + psystem = initPartSys(canvas, 10000) +end + +-- LÖVE callback to update values before each frame +function love.update (dt) + psystem:update(dt) +end + +-- LÖVE callback to draw each frame to the screen +function love.draw () + love.graphics.draw(psystem) +end diff --git a/Task/Pernicious-numbers/11l/pernicious-numbers.11l b/Task/Pernicious-numbers/11l/pernicious-numbers.11l index 2f3f0392ce..c29e11a27e 100644 --- a/Task/Pernicious-numbers/11l/pernicious-numbers.11l +++ b/Task/Pernicious-numbers/11l/pernicious-numbers.11l @@ -1,6 +1,3 @@ -F popcount(n) - R bin(n).count(‘1’) - F is_prime(n) I n < 2 R 0B @@ -12,7 +9,7 @@ F is_prime(n) V i = 0 V cnt = 0 L - I is_prime(popcount(i)) + I is_prime(bits:popcount(i)) print(i, end' ‘ ’) cnt++ I cnt == 25 @@ -21,5 +18,5 @@ L print() L(i) 888888877..888888888 - I is_prime(popcount(i)) + I is_prime(bits:popcount(i)) print(i, end' ‘ ’) diff --git a/Task/Pisano-period/C++/pisano-period.cpp b/Task/Pisano-period/C++/pisano-period.cpp new file mode 100644 index 0000000000..b3e1f964fb --- /dev/null +++ b/Task/Pisano-period/C++/pisano-period.cpp @@ -0,0 +1,138 @@ +#include +#include +#include +#include +#include +using namespace std; + +template +pair floyd(function f, T x0) { + // Floyd's cycle detection algorithm. + auto tortoise = f(x0); + auto hare = f(f(x0)); + while (tortoise != hare) { + tortoise = f(tortoise); + hare = f(f(hare)); + } + + // Find the position μ of first repetition. + unsigned mu = 0; + tortoise = x0; + while (tortoise != hare) { + tortoise = f(tortoise); + hare = f(hare); + mu += 1; + } + + // Find the length of the shortest cycle starting from x_μ + unsigned lam = 1; + hare = f(tortoise); + while (tortoise != hare) { + hare = f(hare); + lam += 1; + } + + return make_pair(lam, mu); +} + +unsigned pisano_period(unsigned p) { + if (p < 2) return 1; + function(pair)> f = [&](auto xy) { + return make_pair(xy.second, (xy.first + xy.second) % p); + }; + return floyd(f, make_pair(0u, 1u)).first; +} + + +bool is_prime(unsigned p) { + if (p < 2) return false; + if (0 == p % 2) return 2 == p; + if (0 == p % 3) return 3 == p; + unsigned d = 5; + while (d * d <= p) { + if (0 == p % d) return false; + d += 2; + if (0 == p % d) return false; + d += 4; + } + return true; +} + +vector> factor(unsigned n) { + vector> ans; + if (n < 2) return ans; + auto work = [&](unsigned p) { + if (0 == n % p) { + unsigned k = 1; + n /= p; + while (0 == n % p) { + k += 1; + n /= p; + } + ans.emplace_back(p, k); + } + }; + work(2); + work(3); + unsigned d = 5; + while (d <= n) { + work(d); + d += 2; + work(d); + d += 4; + } + return ans; +} + +long long ipow(long long p, unsigned k) { + long long ans = 1; + while (0 != k) { + if (0 != k % 2) ans *= p; + k /= 2; + p *= p; + } + return ans; +} + +unsigned pisano_prime(unsigned p, unsigned k) { + if (!is_prime(p) || k == 0) { + return 0; + } + return ipow(p, k - 1) * pisano_period(p); +} +unsigned pisano(unsigned n) { + auto prime_powers{factor(n)}; + unsigned ans = 1; + for (auto [p, k]: prime_powers) { + if (1 < ans) { + ans = lcm(ans, pisano_prime(p, k)); + } else { + ans = pisano_prime(p, k); + } + } + return ans; +} +int main() { + for (unsigned p = 2; p < 15; ++p) { + auto pp = pisano_prime(p, 2); + if (0 < pp) { + cout << "pisanoPrime(" << setw(2) << p << ": 2) = " << pp << endl; + } + } + cout << endl; + for (unsigned p = 2; p < 180; ++p) { + auto pp = pisano_prime(p, 1); + if (0 < pp) { + cout << "pisanoPrime(" << setw(3) << p << ": 1) = " << pp << endl; + } + } + cout << endl; + cout << "pisano(n) for integers 'n' from 1 to 180 are:" << endl; + for (unsigned n = 1; n <= 180; ++n) { + cout << setw(3) << pisano(n) << " "; + if (0 == n % 15) { + cout << endl; + } + } + return 0; +} diff --git a/Task/Population-count/11l/population-count.11l b/Task/Population-count/11l/population-count.11l index 22ca8accdc..ceca338c89 100644 --- a/Task/Population-count/11l/population-count.11l +++ b/Task/Population-count/11l/population-count.11l @@ -1,12 +1,9 @@ -F popcount(n) - R bin(n).count(‘1’) - -print((0.<30).map(i -> popcount(Int64(3) ^ i))) +print((0.<30).map(i -> bits:popcount(Int64(3) ^ i))) [Int] evil, odious V i = 0 L evil.len < 30 | odious.len < 30 - V p = popcount(i) + V p = bits:popcount(i) I (p % 2) != 0 odious.append(i) E diff --git a/Task/Primes---allocate-descendants-to-their-ancestors/Sidef/primes---allocate-descendants-to-their-ancestors.sidef b/Task/Primes---allocate-descendants-to-their-ancestors/Sidef/primes---allocate-descendants-to-their-ancestors.sidef index 045e38d959..7d6f10f92c 100644 --- a/Task/Primes---allocate-descendants-to-their-ancestors/Sidef/primes---allocate-descendants-to-their-ancestors.sidef +++ b/Task/Primes---allocate-descendants-to-their-ancestors/Sidef/primes---allocate-descendants-to-their-ancestors.sidef @@ -24,7 +24,7 @@ for s in (1 .. maxsum) { total += (var dsclen = descendants[s].len) var idx = descendants[s].first_index {|x| x > maxsum } - for d in (descendants[s].slice(0, idx)) { + for d in (descendants[s].first(idx+1)) { ancestors[d] = (ancestors[s] + [s]) } diff --git a/Task/Proper-divisors/Sidef/proper-divisors.sidef b/Task/Proper-divisors/Sidef/proper-divisors.sidef index cdd21e0276..f4bb6cedcd 100644 --- a/Task/Proper-divisors/Sidef/proper-divisors.sidef +++ b/Task/Proper-divisors/Sidef/proper-divisors.sidef @@ -1,5 +1,5 @@ func propdiv (n) { - n.divisors.slice(0, -2) + n.divisors.first(-1) } {|i| printf("%2d: %s\n", i, propdiv(i)) } << 1..10 diff --git a/Task/Pseudo-random-numbers-Middle-square-method/Tcl/pseudo-random-numbers-middle-square-method.tcl b/Task/Pseudo-random-numbers-Middle-square-method/Tcl/pseudo-random-numbers-middle-square-method.tcl new file mode 100644 index 0000000000..166b3f22dc --- /dev/null +++ b/Task/Pseudo-random-numbers-Middle-square-method/Tcl/pseudo-random-numbers-middle-square-method.tcl @@ -0,0 +1,15 @@ +set seed 675248 + +proc rnd {} { + global seed + set s [expr {$seed * $seed}] + while {[string length $s] ne 12} { + set s [string cat 0 $s] + } + set seed [string range $s 3 8] + return $seed +} + +for {set i 0} {$i < 5} {incr i} { + puts [rnd] +} diff --git a/Task/Pseudo-random-numbers-Splitmix64/Odin/pseudo-random-numbers-splitmix64.odin b/Task/Pseudo-random-numbers-Splitmix64/Odin/pseudo-random-numbers-splitmix64.odin new file mode 100644 index 0000000000..27265d669e --- /dev/null +++ b/Task/Pseudo-random-numbers-Splitmix64/Odin/pseudo-random-numbers-splitmix64.odin @@ -0,0 +1,42 @@ +package main + +import "core:fmt" +import "core:math" + +TWO64 :f64: 1 << 64 + +SplitMix64 :: struct { + state: u64, +} + +next_int :: proc(rng: ^SplitMix64) -> u64 { + rng.state += 0x9e3779b97f4a7c15 + z := rng.state + z = (z ~ (z >> 30)) * 0xbf58476d1ce4e5b9 + z = (z ~ (z >> 27)) * 0x94d049bb133111eb + return z ~ (z >> 31) +} + +next_float :: proc(rng: ^SplitMix64) -> f64 { + return f64(next_int(rng)) / TWO64 +} + +main :: proc() { + rng := SplitMix64{1234567} + + for i in 0..<5 { + fmt.println(next_int(&rng)) + } + + rng.state = 987654321 + + vec5 := [5]int{0,0,0,0,0} + for i in 0..<100000 { + j := int(math.floor(next_float(&rng) * 5.)) + vec5[j] += 1 + } + + for v,i in vec5 { + fmt.printf("%d: %d ", i, v) + } +} diff --git a/Task/Ramer-Douglas-Peucker-line-simplification/Sidef/ramer-douglas-peucker-line-simplification.sidef b/Task/Ramer-Douglas-Peucker-line-simplification/Sidef/ramer-douglas-peucker-line-simplification.sidef index 60de074de3..99931f9396 100644 --- a/Task/Ramer-Douglas-Peucker-line-simplification/Sidef/ramer-douglas-peucker-line-simplification.sidef +++ b/Task/Ramer-Douglas-Peucker-line-simplification/Sidef/ramer-douglas-peucker-line-simplification.sidef @@ -1,10 +1,10 @@ func perpendicular_distance(Arr start, Arr end, Arr point) { ((point == start) || (point == end)) && return 0 - var (Δx, Δy ) = ( end »-« start)... - var (Δpx, Δpy) = (point »-« start)... + var (Δx, Δy ) = ( end »-« start)... + var (Δpx, Δpy) = (point »-« start)... var h = hypot(Δx, Δy) [\Δx, \Δy].map { *_ /= h } - (([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).sum.sqrt + (([Δpx, Δpy] »-« ([Δx, Δy] »*» (Δx*Δpx + Δy*Δpy))) »**» 2).sum.sqrt.round(-20) } func Ramer_Douglas_Peucker(Arr points { .all { .len > 1 } }, ε = 1) { @@ -16,8 +16,8 @@ func Ramer_Douglas_Peucker(Arr points { .all { .len > 1 } }, ε = 1) { if (d.max > ε) { var i = d.index(d.max) - return [Ramer_Douglas_Peucker(points.ft(0, i), ε).ft(0, -2)..., - Ramer_Douglas_Peucker(points.ft(i), ε)...] + return [Ramer_Douglas_Peucker(points.first(i), ε).first(-1)..., + Ramer_Douglas_Peucker(points.slice(i), ε)...] } return [points[0,-1]] diff --git a/Task/Sorting-algorithms-Bogosort/Sidef/sorting-algorithms-bogosort.sidef b/Task/Sorting-algorithms-Bogosort/Sidef/sorting-algorithms-bogosort.sidef index cb79f37ff7..9b9e748794 100644 --- a/Task/Sorting-algorithms-Bogosort/Sidef/sorting-algorithms-bogosort.sidef +++ b/Task/Sorting-algorithms-Bogosort/Sidef/sorting-algorithms-bogosort.sidef @@ -1,14 +1,14 @@ func in_order(a) { - return true if (a.len <= 1); - var first = a[0]; - a.ft(1).all { |elem| first <= elem ? do { first = elem; true } : false } + return true if (a.len <= 1) + var first = a[0] + a.last(-1).all { |elem| first <= elem  ? do { first = elem; true } : false } } func bogosort(a) { - a.shuffle! while !in_order(a); - return a; + a.shuffle! while !in_order(a) + return a } -var arr = 5.of{ 100.rand.int }; -say "Before: #{arr}"; -say "After: #{bogosort(arr)}"; +var arr = 5.of { 100.irand } +say "Before: #{arr}" +say "After: #{bogosort(arr)}" diff --git a/Task/Sorting-algorithms-Selection-sort/F-Sharp/sorting-algorithms-selection-sort.fs b/Task/Sorting-algorithms-Selection-sort/F-Sharp/sorting-algorithms-selection-sort.fs index 732fd077c5..a0fc2a7f03 100644 --- a/Task/Sorting-algorithms-Selection-sort/F-Sharp/sorting-algorithms-selection-sort.fs +++ b/Task/Sorting-algorithms-Selection-sort/F-Sharp/sorting-algorithms-selection-sort.fs @@ -3,7 +3,7 @@ let rec ssort = function | x::xs -> let min, rest = List.fold (fun (min,acc) x -> - if h: S o ]) and ((1 < X) and (1 < Y) (and=. *.) (X < Y)) o ]) +filter0=. candidates o (constraints # ]) + +(sd=. S "0 _ < o pmtod) ; o # sd) + +filter2=. candidates o ; o (pd #~ 1 = (#&>) o pd) +filter3=. candidates o ; o (sd #~ 1 = (#&>) o sd) + +decompositions=. > o , o { o (;~) o i. +show=. 'X=' , ": o X ,' Y=' , ": o Y , ' X+Y=' , ": o (X+Y) , ' X*Y=' , ": o (X*Y) + +solve=. show :: (''"_) o filter3 o filter2 o filter1 o (] filter0 decompositions) f. diff --git a/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-2.j b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-2.j new file mode 100644 index 0000000000..d9193f8eb0 --- /dev/null +++ b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-2.j @@ -0,0 +1,34 @@ + solve 100 +2352 candidates +145 candidates +86 candidates +1 candidates +X=4 Y=13 X+Y=17 X*Y=52 + + solve 64 +930 candidates +62 candidates +46 candidates +0 candidates + + + solve 1685 +707281 candidates +51011 candidates +17567 candidates +2 candidates +X=4 4 Y=13 61 X+Y=17 65 X*Y=52 244 + + solve 1970 +967272 candidates +70475 candidates +23985 candidates +3 candidates +X=4 4 16 Y=13 61 73 X+Y=17 65 89 X*Y=52 244 1168 + + solve 2522 +1586340 candidates +116238 candidates +37748 candidates +4 candidates +X=4 4 16 16 Y=13 61 73 111 X+Y=17 65 89 127 X*Y=52 244 1168 1776 diff --git a/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-3.j b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-3.j new file mode 100644 index 0000000000..e9fcd06730 --- /dev/null +++ b/Task/Sum-and-product-puzzle/J/sum-and-product-puzzle-3.j @@ -0,0 +1,10 @@ + _80 [\ (5!:5)<'solve' +('X=' , ":@:(0&{"1) , ' Y=' , ":@:(1&{"1) , ' X+Y=' , ":@:(0&{"1 + 1&{"1) , ' X* +Y=' , ":@:(0&{"1 * 1&{"1)) ::(''"_)@:(([ 0 0&$@(1!:2&2)@:(' candidates' ,~ ":@:# +))@:;@:(((0&{"1 + 1&{"1) @:((0&{"1 + 1&{"1) @:(( +0&{"1 * 1&{"1) "0 _ <@:((0&{"1 * 1&{"1)@:;@:(((0 +&{"1 * 1&{"1) : (0&{"1 + 1&{"1)@:]) +*. ((1 < 0&{"1) *. (1 < 1&{"1) *. 0&{"1 < 1&{"1)@:]) # ]) >@:,@:{@:(;~)@:i.) diff --git a/Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rust b/Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rust new file mode 100644 index 0000000000..27776a5397 --- /dev/null +++ b/Task/Sum-and-product-puzzle/Rust/sum-and-product-puzzle.rust @@ -0,0 +1,53 @@ +use primes::is_prime; + +fn satisfy1(x: u64) -> bool { + let upper_limit = (x as f64).sqrt() as u64 + 1; + for i in 2..upper_limit { + if is_prime(i) && is_prime(x - i) { + return false; + } + } + return true; +} + +fn satisfy2(x: u64) -> bool { + let mut once: bool = false; + let upper_limit = (x as f64).sqrt() as u64 + 1; + for i in 2..upper_limit { + if x % i == 0 { + let j = x / i; + if 2 < j && j < 100 && satisfy1(i + j) { + if once { + return false; + } + once = true; + } + } + } + return once +} + +fn satisfyboth(x: u64) -> u64 { + if !satisfy1(x) { + return 0; + } + let mut found = 0; + for i in 2..=(x/2) { + if satisfy2(i * (x - i)) { + if found > 0 { + return 0; + } + found = i; + } + } + return found; +} + +fn main() { + for i in 2..100 { + let j = satisfyboth(i); + if j > 0 { + println!("Solution: ({}, {})", j, i - j); + } + } +} diff --git a/Task/Thue-Morse/11l/thue-morse.11l b/Task/Thue-Morse/11l/thue-morse.11l index e07510fa72..4c9d556b71 100644 --- a/Task/Thue-Morse/11l/thue-morse.11l +++ b/Task/Thue-Morse/11l/thue-morse.11l @@ -1,4 +1,4 @@ F thue_morse_digits(digits) - R (0 .< digits).map(n -> bin(n).count(‘1’) % 2) + R (0 .< digits).map(n -> bits:popcount(n) % 2) print(thue_morse_digits(20)) diff --git a/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 b/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 new file mode 100644 index 0000000000..f7285909d7 --- /dev/null +++ b/Task/Trabb-Pardo-Knuth-algorithm/Modula-2/trabb-pardo-knuth-algorithm.mod2 @@ -0,0 +1,72 @@ +MODULE TrabbPardoKnuth; + +FROM STextIO IMPORT + SkipLine, WriteString, WriteLn; +FROM SRealIO IMPORT + ReadReal, WriteFixed; +FROM SWholeIO IMPORT + WriteInt; +FROM RealMath IMPORT + sqrt; + +CONST + Size = 11; + +TYPE + TSequence = ARRAY [1 .. Size] OF REAL; + +VAR + S: TSequence; + I: CARDINAL; + Result: REAL; + +PROCEDURE ReverseSequence(VAR S: TSequence); +VAR + I: CARDINAL; + Temp: REAL; +BEGIN + FOR I := 1 TO Size DIV 2 DO + Temp := S[I]; + S[I] := S[Size - I + 1]; + S[Size - I + 1] := Temp; + END; +END ReverseSequence; + +PROCEDURE RealAbs(Item: REAL): REAL; +BEGIN + IF Item < 0.0 THEN + RETURN -Item + ELSE + RETURN Item + END +END RealAbs; + +PROCEDURE DoOperation(Item: REAL): REAL; +BEGIN + RETURN sqrt(RealAbs(Item)) + 5.0 * Item * Item * Item; +END DoOperation; + +BEGIN + WriteString("Enter 11 numbers."); + WriteLn; + FOR I := 1 TO Size DO + WriteInt(I, 2); + WriteString(": "); + ReadReal(S[I]); + SkipLine + END; + ReverseSequence(S); + WriteLn; + FOR I := 1 TO Size DO + Result := DoOperation(S[I]); + WriteString("f("); + WriteFixed(S[I], 3, 8); + WriteString(") = "); + IF Result > 400.0 THEN + WriteString("overflow"); + ELSE + WriteFixed(Result, 3, 8) + END; + WriteLn; + END; +END TrabbPardoKnuth. diff --git a/Task/Van-Eck-sequence/Sidef/van-eck-sequence.sidef b/Task/Van-Eck-sequence/Sidef/van-eck-sequence.sidef index fc5497fef7..3e00cd1175 100644 --- a/Task/Van-Eck-sequence/Sidef/van-eck-sequence.sidef +++ b/Task/Van-Eck-sequence/Sidef/van-eck-sequence.sidef @@ -14,4 +14,4 @@ func van_eck(n) { } say van_eck(10) -say van_eck(1000).slice(991-1, 1000-1) +say van_eck(1000).last(10) diff --git a/Task/Verify-distribution-uniformity-Chi-squared-test/C++/verify-distribution-uniformity-chi-squared-test.cpp b/Task/Verify-distribution-uniformity-Chi-squared-test/C++/verify-distribution-uniformity-chi-squared-test.cpp index c13f1698fa..00b163dd66 100644 --- a/Task/Verify-distribution-uniformity-Chi-squared-test/C++/verify-distribution-uniformity-chi-squared-test.cpp +++ b/Task/Verify-distribution-uniformity-Chi-squared-test/C++/verify-distribution-uniformity-chi-squared-test.cpp @@ -5,7 +5,7 @@ void print_vector(const std::vector& list) { std::cout << "["; - for ( uint64_t i = 0; i < list.size(); ++i ) { + for ( uint64_t i = 0; i < list.size() - 1; ++i ) { std::cout << list[i] << ", "; } std::cout << list.back() << "]" << std::endl; diff --git a/Task/War-card-game/Applesoft-BASIC/war-card-game-1.basic b/Task/War-card-game/Applesoft-BASIC/war-card-game-1.basic index 12200de58b..3b1c8c767a 100644 --- a/Task/War-card-game/Applesoft-BASIC/war-card-game-1.basic +++ b/Task/War-card-game/Applesoft-BASIC/war-card-game-1.basic @@ -6,70 +6,85 @@ 150 SUIT$ = "CDHS" 160 FACE$ = "23456789TJQKA" 170 M = LEN (SUIT$) - 180 FOR I = 1 TO D: FOR S = 1 TO M: FOR F = 1 TO LEN (FACE$):DECK$ = DECK$ + CHR$ ((F - 1) * M + (S - 1)): NEXT F,S,I + 180 FOR I = 1 TO D: FOR S = 1 TO M: FOR F = 1 TO LEN (FACE$):P$ = P$ + CHR$ ((F - 1) * M + (S - 1)): NEXT F,S,I 190 TEXT : HOME : POKE 34,12 - REM INITIALIZE - 200 N = LEN (DECK$) - 210 PRINT "SHUFFLING ..." - 220 FOR I = 1 TO N - 230 R = INT ( RND (1) * N + 1) - 240 R$ = MID$ (DECK$,R,1) - 250 C$ = MID$ (DECK$,I,1) - 260 DECK$ = MID$ (DECK$,1,I - 1) + R$ + MID$ (DECK$,I + 1) - 270 DECK$ = MID$ (DECK$,1,R - 1) + C$ + MID$ (DECK$,R + 1) - 280 NEXT REM DEAL TO PLAYERS - 300 E = INT (N / P) - 310 FOR I = 1 TO P - 320 D$(I) = MID$ (DECK$,(I - 1) * E + 1,E) - 330 NEXT - 340 P$ = MID$ (DECK$,(I - 1) * E + 1): REM WINNER OF THE FIRST PLAY KEEPS THESE REMAINING CARDS - 350 P$ = "": REM REMOVE REMAINING CARDS FROM THE GAME + 200 GOSUB 700"SHUFFLE + 210 E = INT (N / P) + 220 FOR I = 1 TO P + 230 D$(I) = MID$ (P$,(I - 1) * E + 1,E) + 240 NEXT + 250 P$ = MID$ (P$,(I - 1) * E + 1): REM WINNER OF THE FIRST PLAY KEEPS THESE REMAINING CARDS + 260 P$ = "": REM REMOVE REMAINING CARDS FROM THE GAME REM PLAY - 400 FOR T = 0 TO 1E38 - 410 GOSUB 500"TURN - 420 IF Q = 0 THEN NEXT T - 430 PRINT TAB( 10)"IN "T" TURNS": TEXT : VTAB 11: PRINT : CALL - 868: PRINT "...": VTAB 23 - 440 END + 300 FOR T = 0 TO 1E38 + 310 GOSUB 400"TURN + 320 IF Q = 0 THEN NEXT T + 330 PRINT " IN "T" TURNS": TEXT : VTAB 11: PRINT : CALL - 868: PRINT "...": VTAB 23 + 340 END REM TURN - 500 GOSUB 800"IS GAME OVER? - 510 IF Q THEN RETURN - 520 U = 0: REM UTMOST CARD - 530 C = 0: REM COUNT THE PLAYERS WITH THE UTMOST CARD - 540 FOR I = 1 TO P - 550 C$(I) = MID$ (D$(I),1,1) - 560 IF LEN (C$(I)) AND (R OR NOT L(I)) THEN GOSUB 700"draw card + 400 PRINT : GOSUB 900"IS GAME OVER? + 410 IF Q THEN RETURN + 420 U = 0: REM UTMOST CARD + 430 C = 0: REM COUNT THE PLAYERS WITH THE UTMOST CARD + 440 FOR I = 1 TO P + 450 C$(I) = "" : IF NOT L(I) THEN C$(I) = MID$ (D$(I),1,1) + 460 IF LEN (C$(I)) THEN GOSUB 800"DRAW CARD + 470 NEXT I + 480 IF C = 1 GOTO 600"WINNER TAKE CARDS + 490 FOR I = 1 TO P:L(I) = G(I) < > U: NEXT I + 500 PRINT "WAR! "; + 510 GOSUB 900"IS GAME OVER? + 520 IF Q THEN RETURN + 530 C = 0 + 540 FOR I = 1 TO P:P$ = P$ + C$(I): NEXT I + 550 FOR I = 1 TO P + REM DOES NOT APPLY TO 2 PLAYER GAMES (BICYCLE RULE): Y MEANS IGNORE THE RULE THAT ONLY THE WINNERS PLACE CARD(S) FACE DOWN + 560 IF Y OR NOT L(I) THEN FOR J = 1 TO W:C$ = MID$ (D$(I),1,1) :C = C + LEN(C$) : P$ = P$ + C$ :D$(I) = MID$ (D$(I),2): NEXT J 570 NEXT I - 580 IF C = 1 THEN PRINT "PLAYER "A" TAKES THE CARDS.": FOR I = 1 TO P:L(I) = 0:D$(A) = D$(A) + C$(I): NEXT I:D$(A) = D$(A) + P$:P$ = "": RETURN - 590 FOR I = 1 TO P:L(I) = G(I) < > C: NEXT I - 600 PRINT "TIE!" - 610 GOSUB 800"IS GAME OVER? - 620 IF Q THEN RETURN - 630 FOR I = 1 TO P:P$ = P$ + C$(I): NEXT I - 640 FOR I = 1 TO P - REM DOES NOT APPLY TO 2 PLAYER GAMES (BICYCLE RULE): R MEANS IGNORE THE RULE THAT ONLY THE WINNERS PLACE CARD(S) FACE DOWN - 650 IF R OR NOT L(I) THEN FOR J = 1 TO W:P$ = P$ + MID$ (D$(I),1,1):D$(I) = MID$ (D$(I),2): PRINT " ? ";: NEXT J - 660 NEXT I - 670 PRINT "CARDS ARE FACE DOWN." + 580 PRINT C" CARDS PLACED FACE DOWN."; + 590 RETURN + + REM WINNER TAKE CARDS + 600 FOR I = 1 TO P + 610 L(I) = 0 + 620 P$ = P$ + C$(I) + 630 NEXT I + 640 PRINT "PLAYER "A" TAKES "LEN(P$); + 650 IF NOT Z THEN GOSUB 710"SHUFFLE + 660 D$(A) = D$(A) + P$ + 670 P$ = "" 680 RETURN + REM SHUFFLE + 700 PRINT "SHUFFLING "; + 710 N = LEN (P$) + 720 FOR I = 1 TO N + 730 IF I - INT (I / 4) * 4 = 1 THEN PRINT "."; + 740 R = INT ( RND (1) * N + 1) + 750 R$ = MID$ (P$,R,1) : C$ = MID$ (P$,I,1) + 760 P$ = MID$ (P$,1,I - 1) + R$ + MID$ (P$,I + 1) + 770 P$ = MID$ (P$,1,R - 1) + C$ + MID$ (P$,R + 1) + 780 NEXT + 790 RETURN + REM DRAW CARD - 700 G = ASC (C$(I)) - 710 G(I) = INT (G / M) + 1 - 720 PRINT MID$ (FACE$,G(I),1) MID$ (SUIT$,G - (G(I) - 1) * M + 1,1)" "; - 730 D$(I) = MID$ (D$(I),2) - 740 C = C + (G(I) = U) - 750 IF G(I) > U THEN U = G(I):C = 1:A = I - 760 RETURN + 800 G = ASC (C$(I)) + 810 G(I) = INT (G / M) + 1 + 820 PRINT MID$ (FACE$,G(I),1) MID$ (SUIT$,G - (G(I) - 1) * M + 1,1)" "; + 830 D$(I) = MID$ (D$(I),2) + 840 C = C + (G(I) = U) + 850 IF G(I) > U THEN U = G(I):C = 1:A = I + 860 RETURN REM IS GAME OVER? - 800 C = 0 - 810 FOR I = 1 TO P - 820 IF LEN (D$(I)) THEN A = I:C = C + 1 - 830 NEXT I - 840 IF C > 1 THEN RETURN + 900 C = 0 + 910 FOR I = 1 TO P + 920 IF LEN (D$(I)) THEN A = I:C = C + 1 + 930 NEXT I + 940 IF C > 1 THEN RETURN REM GAME OVER - WHO WON MESSAGE - 850 Q = 1 - 860 IF C THEN PRINT "PLAYER "A" WINS THE GAME.": RETURN - 870 PRINT "GAME ENDS AS A TIE.": RETURN + 950 Q = 1 + 960 IF C THEN PRINT "PLAYER "A" WINS THE GAME";: RETURN + 970 PRINT "GAME ENDS AS A TIE";: RETURN diff --git a/Task/War-card-game/Applesoft-BASIC/war-card-game-2.basic b/Task/War-card-game/Applesoft-BASIC/war-card-game-2.basic index 84eb33a24b..c0cdc8beb1 100644 --- a/Task/War-card-game/Applesoft-BASIC/war-card-game-2.basic +++ b/Task/War-card-game/Applesoft-BASIC/war-card-game-2.basic @@ -1 +1 @@ -CLEAR : R = RND ( - 5) : GOTO 110 +CLEAR : R = RND ( - 58) : GOTO 110 diff --git a/Task/Weird-numbers/Sidef/weird-numbers.sidef b/Task/Weird-numbers/Sidef/weird-numbers.sidef index 51475a5be6..680dc1361c 100644 --- a/Task/Weird-numbers/Sidef/weird-numbers.sidef +++ b/Task/Weird-numbers/Sidef/weird-numbers.sidef @@ -1,4 +1,4 @@ -func is_pseudoperfect(n, d = n.divisors.slice(0, -2), s = d.sum, m = d.end) { +func is_pseudoperfect(n, d = n.divisors.first(-1), s = d.sum, m = d.end) { return false if (m < 0) @@ -13,7 +13,7 @@ func is_pseudoperfect(n, d = n.divisors.slice(0, -2), s = d.sum, m = d.end) { } func is_weird(n) { - (n.sigma > 2*n) && !is_pseudoperfect(n) + (n.sigma > 2*n) && !is_pseudoperfect(n) } var w = (1..Inf -> lazy.grep(is_weird).first(25)) diff --git a/Task/Wireworld/Raku/wireworld.raku b/Task/Wireworld/Raku/wireworld.raku index 33c7303d98..06b63047eb 100644 --- a/Task/Wireworld/Raku/wireworld.raku +++ b/Task/Wireworld/Raku/wireworld.raku @@ -1,9 +1,9 @@ class Wireworld { has @.line; - method height () { @!line.elems } - has int $.width; + method height returns Int { @!line.elems } + method width returns Int { max @!line».chars } - multi method new(@line) { samewith :@line, :width(max @line».chars) } + multi method new(@line) { samewith :@line } multi method new($str ) { samewith $str.lines } method gist { join "\n", @.line } @@ -21,7 +21,7 @@ class Wireworld { my @succ; for ^$.height X ^$.width -> ($i, $j) { @succ[$i] ~= - do given @!line[$i].comb[$j] { + do given @.line[$i].comb[$j] { when 'H' { 't' } when 't' { '.' } when '.' { @@ -50,13 +50,17 @@ multi sub MAIN ( Numeric:D :$interval = 1/4, Bool :$stop-on-repeat, ) { - run-loop :$interval, :$stop-on-repeat, Wireworld.new: Q:to/END/ - tH......... - . . - ... - . . - Ht.. ...... - END + run-loop + :$interval, + :$stop-on-repeat, + Wireworld.new: + Q:to/§/ + tH......... + . . + ... + . . + Ht.. ...... + § } sub run-loop ( @@ -66,16 +70,11 @@ sub run-loop ( ){ my %seen is SetHash; + print "\e7"; # save cursor position for $initial ...^ * eqv * { # generate a sequence (uses .succ) - print "\e[2J"; - say '#' x $initial.width; - .say; - say '#' x $initial.width; - - if $stop-on-repeat { - last if %seen{ .gist }++; - } - - sleep $interval; + print "\e8"; # restore cursor position + .say; + last if $stop-on-repeat and %seen{ .gist }++; + sleep $interval; } } diff --git a/Task/Wireworld/Sidef/wireworld.sidef b/Task/Wireworld/Sidef/wireworld.sidef index 0fde9dcce4..3e1021c613 100644 --- a/Task/Wireworld/Sidef/wireworld.sidef +++ b/Task/Wireworld/Sidef/wireworld.sidef @@ -1,26 +1,26 @@ -var f = [[], DATA.lines.map {['', .chars..., '']}..., []]; +var f = [[], DATA.lines.map {['', .chars..., '']}..., []] 10.times { - say f.map { .join(" ") + "\n" }.join; - var a = [[]]; - for y in (1 .. f.end-1) { - var r = f[y]; - var rr = ['']; - for x in (1 .. r.end-1) { - var c = r[x]; + say f.map { .join(" ") + "\n" }.join + var a = [[]] + for y in (1 ..^ f.end) { + var r = f[y] + var rr = [''] + for x in (1 ..^ r.end) { + var c = r[x] rr << ( given(c) { when('H') { 't' } when('t') { '.' } - when('.') { <. H>[f.ft(y-1, y+1).map{.ft(x-1, x+1)...}.count('H') ~~ [1,2]] } + when('.') { <. H>[[f[y-1 .. y+1]].map{.[x-1 .. x+1]}.count('H') ~~ [1,2]] } default { c } } ) } - rr << ''; - a << rr; + rr << '' + a << rr } - f = [a..., []]; + f = [a..., []] } __DATA__ diff --git a/Task/Word-wrap/Sidef/word-wrap-1.sidef b/Task/Word-wrap/Sidef/word-wrap-1.sidef index ba9339ffdf..5a6f486ed1 100644 --- a/Task/Word-wrap/Sidef/word-wrap-1.sidef +++ b/Task/Word-wrap/Sidef/word-wrap-1.sidef @@ -1,18 +1,18 @@ class String { method wrap(width) { - var txt = self.gsub(/\s+/, " "); - var len = txt.len; - var para = []; - var i = 0; + var txt = self.gsub(/\s+/, " ") + var len = txt.len + var para = [] + var i = 0 while (i < len) { - var j = (i + width); - while ((j < len) && (txt.char_at(j) != ' ')) { --j }; - para.append(txt.substr(i, j-i)); - i = j+1; - }; - return para.join("\n"); + var j = (i + width) + while ((j < len) && (txt.char_at(j) != ' ')) { --j } + para.append(txt.substr(i, j-i)) + i = j+1 + } + return para.join("\n") } } -var text = 'aaa bb cc ddddd'; -say text.wrap(6); +var text = 'aaa bb cc ddddd' +say text.wrap(6) diff --git a/Task/Word-wrap/Sidef/word-wrap-2.sidef b/Task/Word-wrap/Sidef/word-wrap-2.sidef index 30f5d611a2..e32619739a 100644 --- a/Task/Word-wrap/Sidef/word-wrap-2.sidef +++ b/Task/Word-wrap/Sidef/word-wrap-2.sidef @@ -24,7 +24,7 @@ class SmartWordWrap { root << [ array.first(i+1).join(' '), - self.prepare_words(array.ft(i+1), depth+1, callback) + self.prepare_words(array.slice(i+1), depth+1, callback) ] if (depth.is_zero) { @@ -67,7 +67,7 @@ class SmartWordWrap { self.prepare_words(words, callback: { |path| self.combine([], path, { |combination| var score = 0 - combination.ft(0, -2).each { |line| + combination.first(-1).each { |line| score += (width - line.len -> sqr) } @@ -82,9 +82,9 @@ class SmartWordWrap { } } -var sww = SmartWordWrap(); +var sww = SmartWordWrap() -var words = %w(aaa bb cc ddddd); -var wrapped = sww.wrap(words, 6); +var words = %w(aaa bb cc ddddd) +var wrapped = sww.wrap(words, 6) -say wrapped; +say wrapped